ASP.NET MVC实体框架跨上下文和程序集连接实体

时间:2015-08-25 13:46:38

标签: asp.net asp.net-mvc entity-framework asp.net-identity

我有一个MVC 5项目,我把我的模型分成了一个完全不同的项目,比如Project.Models。 Identity(ApplicationUser)模型及其DbContext仍然在主项目中,如默认的MVC 5项目脚手架中所示。 Project.Models程序集中的一个实体必须具有属性,该属性是ApplicationUsers列表。

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

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

感谢。

1 个答案:

答案 0 :(得分:1)

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

您还可以在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类中的 IdentityDbContext 继承。像这样:

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

这样您就不需要在上下文类中定义DbSet<MainProject.ApplicationUser>

相关问题