【发布时间】:2015-09-17 21:49:41
【问题描述】:
我正在一个系统中实现 ASP.NET 身份,该系统使用带有实体框架的用户模型进行身份验证,并在 WebApp 中由 Session 控制(是的,它是 Web 表单的遗留系统),我们实现了,替换了 User由身份的ApplicationUser 建模,一切正常。
问题是,有一个通知系统,基本上是Notification和User模型之间的多对多关系,
这些通知与系统的其余部分一起保存在 SQL Server 中,但也位于缓存 Redis 中以加快读取速度,并且需要对其进行序列化以进行写入。我们删除了User 模型,然后在ApplicationUser 中添加了ICollection 和Notification 模型,反之亦然 - 使两者之间产生关联。
但是ApplicationUser继承自IdentityUser,甚至添加注解[Serializable]我得到了异常:
键入“Microsoft.AspNet.Identity.EntityFramework.IdentityUser” 程序集 'Microsoft.AspNet.Identity.EntityFramework,版本 = 2.0.0.0,Culture = 中性,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; }
}
Serialize 方法用于将对象序列化到 Redis(抛出异常的地方)
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;
}
}
【问题讨论】:
-
没有标记为Serializable,可以看源码:aspnetidentity.codeplex.com/SourceControl/latest#src/…
-
嗯我明白了,好吧,我会做 decyclone 建议,谢谢!
标签: c# asp.net entity-framework serialization asp.net-identity