将ASP.Net Identity DbContext与我的DbContext合并

dre*_*wob 8 c# asp.net asp.net-mvc entity-framework

我在Visual Studio中使用默认的ASP.Net MVC模板.我正在使用在模板中为我创建的ASP.Net Identity代码.我想用DBContext来了解ApplicationUser实体(AspNetUser表)和其他实体之间的关系.例如,我希望能够拥有一个ApplicationUser.Messages属性,该属性展示了ApplicationUser和Message实体之间的关系.我有一个数据访问层项目中所有非身份实体的DbContext.模板ApplicationDbContext位于UI层中.为了保持Identity实体和我的自定义实体之间的关系,我需要合并到一个DbContext中,对吗?我该怎么做呢?

以下是我的一些示例代码:

使用我的自定义Messages属性从MVC模板在UI Layer项目中为我创建的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();
    }
}
Run Code Online (Sandbox Code Playgroud)

我在域/业务逻辑层中的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; }
}
Run Code Online (Sandbox Code Playgroud)

我在数据访问层项目中的DBContext:

public class PSNContext : DbContext, IPSNContext
{
    public PSNContext()
        :base ("DefaultConnection")
    {
    }

    public DbSet<Message> Messages { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

将UI特定的代码从UI层中的ApplicationUser引入我的业务逻辑层是不对的:

var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
Run Code Online (Sandbox Code Playgroud)

有一个更好的方法吗?

小智 2

这已经在这里得到了回答

至于把ApplicationUser移到逻辑层,我个人认为还是可以的。那里的逻辑不使用特定于 Web 的命名空间。正在使用的与 Microsoft.AspNet.Identity 和 System.Security.Claims 相关。在本例中,ApplicationUser 是实体,您的 Web 层应使用 ClaimsPrincipal 进行身份验证和授权。

如果您想要一个示例,我之前已经完成过此合并。尽管它并不处于理想状态,但它应该作为您想要实现的目标的示例。