[英]Foreign Key To Microsoft.AspNet.Identity.EntityFramework.IdentityUser?
[英]'Microsoft.AspNet.Identity.EntityFramework.IdentityUser' is not marked as serializable
我正在一個系統中實現ASP.NET Identity,在該系統中,使用了帶有Entity Framework的用戶模型進行身份驗證,並由Session在WebApp中進行了控制(是的,這是Web表單中的遺留系統),我們實現了,將User
模型替換為Identity的ApplicationUser
,一切正常。
問題是,有一個通知系統,它基本上是Notification
和User
模型之間的多對多關系,這些通知與系統的其余部分一起保存在SQL Server中,但也保存在緩存Redis中,以加快讀取速度並且需要對其進行序列化以進行編寫。 我們刪除了User
模型,然后在Notification
模型中添加了ApplicationUser
的ICollection
,反之亦然-兩者之間建立了聯系。
但是ApplicationUser
繼承自IdentityUser
,甚至添加了注釋[Serializable]
我得到了一個例外:
類型'Microsoft.AspNet.Identity.EntityFramework.IdentityUser'程序集'Microsoft.AspNet.Identity.EntityFramework,版本= 2.0.0.0,區域性=中性,PublicKeyToken = 31bf3856ad364e35'未標記為可序列化
我的問題是,有什么方法可以序列化嗎? 還是我將不得不創建另一個僅與通知模型相關的用戶模型?
ApplicationUser
模型
[Serializable]
public class ApplicationUser : IdentityUser
{
public ApplicationUser()
{
this.Notificacoes = new List<Notificacao>();
}
public ClaimsIdentity GenerateUserIdentity(IdentityConfig.ApplicationUserManager manager)
{
var userIdentity = manager.CreateIdentity(this, DefaultAuthenticationTypes.ApplicationCookie);
return userIdentity;
}
public Task<ClaimsIdentity> GenerateUserIdentityAsync(IdentityConfig.ApplicationUserManager manager)
{
return Task.FromResult(GenerateUserIdentity(manager));
}
public bool ReceiveNotifications { get; set; }
public int Permission { get; set; }
public virtual ICollection<Notificacao> Notificacoes { get; set; }
}
Notification
模型
[Serializable]
public partial class Notificacao
{
public Notificacao()
{
this.Usuarios = new List<ApplicationUser>();
}
public int Codigo { get; set; }
public string Mensagem { get; set; }
public DateTime DataHoraNotificacao { get; set; }
public int Tipo { get; set; }
public virtual ICollection<ApplicationUser> Usuarios { get; set; }
}
用於將對象序列化為Redis的Serialize方法(引發異常的地方)
static byte[] Serialize(object o)
{
if (o == null)
{
return null;
}
BinaryFormatter binaryFormatter = new BinaryFormatter();
using (MemoryStream memoryStream = new MemoryStream())
{
binaryFormatter.Serialize(memoryStream, o);
byte[] objectDataAsStream = memoryStream.ToArray();
return objectDataAsStream;
}
}
由於您無法控制包含IdentityUser類的組件,因此無法執行此操作。 另一種解決方案是在緩存之前將對象映射到Dto(數據傳輸對象),而在獲取時將其映射。
關於此主題的其他主題(與WCF相關,但仍涉及序列化IdentityUser):
您不想將IdentityUser或其任何子類序列化到數據庫。 期。
如果需要維護數據庫中的關系,請創建POCO (普通的舊CLR對象-簡單來說就是自定義類)。
另外,如果您需要在用戶類中攜帶IdentityUser ,請使用composition而不是繼承 。 這意味着,不要從IdentityUser繼承,而是在您的類中創建它的屬性。 並將該屬性標記為NonSerializable 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.