EF6多租户上下文之间的关系

时间:2013-11-22 16:15:31

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

我想在我的mvc5应用程序中使用IdentityDbContext来保护我的安全。我的应用程序的datacontext应该与IdentityDbContext中我的IdentityUser子类有关系。当我尝试创建这些关系时(多对多:一个MyIdentityUser有很多Foo,一个Foo有很多MyIdentityUser),我得到'无键定义'错误:
MyNamespace.IdentityUserLogin: : EntityType 'IdentityUserLogin' has no key defined. Define the key for this EntityType.

This Question似乎表明我会以错误的方式解决它,而应该创建一个包含所有内容的单个上下文。我的问题是:让单个数据库托管MVC5安全类型(所以我可以使用UserManager,授权属性等)以及其他应用程序数据的正确方法是什么?

我应该将IdentityDbContext子类化为我的'超级模型'吗?尝试在IdentityDbContext中重新创建实体和映射?还有别的吗?

1 个答案:

答案 0 :(得分:1)

创建以下两个类

public class IdentityUserLoginConfiguration : EntityTypeConfiguration<IdentityUserLogin>
{

    public IdentityUserLoginConfiguration()
    {
        HasKey(iul => iul.UserId);
    }

}

public class IdentityUserRoleConfiguration : EntityTypeConfiguration<IdentityUserRole>
{

    public IdentityUserRoleConfiguration()
    {
        HasKey(iur => iur.RoleId);
    }

}

在Applications DbContext中的OnModelCreating方法中,将上面列出的两个配置添加到模型中:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {

        modelBuilder.Configurations.Add(new IdentityUserLoginConfiguration());
        modelBuilder.Configurations.Add(new IdentityUserRoleConfiguration());

    }

现在应该在创建模型时摆脱错误方法。它确实适合我。