[英]Merging ASP.Net Identity DbContext with my DbContext
我在Visual Studio中使用默认的ASP.Net MVC模板。 我正在使用在模板中为我创建的ASP.Net Identity代码。 我希望使用DBContext来了解ApplicationUser实体(AspNetUser表)与其余实体之间的关系。 例如,我希望能够有一个ApplicationUser.Messages属性,该属性显示ApplicationUser和Message实体之间的关系。 我在数据访问层项目中拥有所有非身份实体的DbContext。 模板ApplicationDbContext在UI层中。 为了保持身份实体和自定义实体之间的关系,我需要合并到一个DbContext中,对吗? 我该怎么做呢?
这是我所拥有的一些示例代码:
使用我的自定义Messages属性从MVC模板在UI层项目中为我创建的IdentityUser和DbContext:
public class ApplicationUser : IdentityUser
{
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
{
// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
// Add custom user claims here
return userIdentity;
}
public ICollection<Message> Messages { get; set; }
}
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("DefaultConnection", throwIfV1Schema: false)
{
}
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
}
我在域/业务逻辑层中拥有的Message类:
public class Message
{
public int Id { get; set; }
[Required]
public string Title { get; set; }
[Required]
public string Body { get; set; }
[Required]
public DateTime Created { get; set; }
}
我在数据访问层项目中拥有的DBContext:
public class PSNContext : DbContext, IPSNContext
{
public PSNContext()
:base ("DefaultConnection")
{
}
public DbSet<Message> Messages { get; set; }
}
将这样的特定于UI的代码从UI层的ApplicationUser引入我的业务逻辑层是不合适的:
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
有一个更好的方法吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.