ASP.NET MVC Entity Framework 跨上下文和程序集加入实体

ASP.NET MVC Entity Framework Join Entities Across contexts and assemblies

我有一个 MVC 5 项目,我在其中将我的模型分离到一个单独的项目中,比如说 Project.Models。 Identity (ApplicationUser) 模型及其 DbContext 仍在主项目中,如默认 MVC 5 项目脚手架中所示。 Project.Models 程序集中的实体之一必须有一个 属性,它是一个 ApplicationUsers 列表。

现在我开始认为将实体模型分离到一个单独的项目中并不是一个好主意,因为现在我在单独的上下文和程序集中拥有实体模型和身份模型。

如果 ApplicaitonUsers 在单独的程序集中,我如何才能使 ApplicaitonUsers 列表成为实体对象的一部分?我应该将项目合并回一个程序集和 DbContexgt 还是有一种简单的方法来解决这个问题?我无法在 Project.Models 的 DbContext 中定义 DbSet<MainProject.ApplicationUser>,因为这意味着循环引用。

谢谢。

您可以在模型项目中添加与身份相关的包 Microsoft.AspNet.IdentityMicrosoft.AspNet.Identity.EntityFramework,并将 ApplicationUser class 移动到模型项目。

您还可以像这样在 ApplicationUser 中添加配置文件数据:

public class ApplicationUser : IdentityUser
{
    public string FirstName { get; set; }
    public string LastName { get; set; }

    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser, string> 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;
    }
}

此外,要使其成为单个 DBContext,您可以在您的 dbcontext class 中直接从 IdentityDbContext 继承。像这样:

public partial class MyDBContext : IdentityDbContext<ApplicationUser>
{
    public MyDBContext()
        : base("name=DefaultConnection", throwIfV1Schema: false)
    {
    }
}

这样您就不需要在上下文 class.

中定义 DbSet<MainProject.ApplicationUser>