首页 文章

我可以为asp身份使用相同的dbcontext吗?

提问于
浏览
1

是否有可能告诉asp身份使用与应用程序dbcontext相同的dbcontext?我的表需要与身份表相关 . 每个表都有createuser和edituser字段,链接到标识表 . 如果asp使用自己的dbcontext,那么我还必须将实体和映射到身份表添加到应用程序dbcontext . 对于这种情况,这是一种更好的方法吗?我首先使用实体框架代码6和asp mvc 5 .

EDIT

根据下面的答案,只要我的dbcontext继承自IdentityContext,我就可以使用相同的dbcontext .

我的问题:

我还需要手动创建实体类和 Map 吗?如何将我的表之间的关系映射到identityuser?

这是我目前的dbcontext

public partial class MyContext : DbContext
{
    static MyContext()
    {
        Database.SetInitializer<MyContext>(null);
    }

    public MyContext()
        : base("Name=MyContext")
    {
        this.Configuration.ProxyCreationEnabled = false;
        this.Configuration.LazyLoadingEnabled = false;
    }

    public new DbSet<TEntity> Set<TEntity>() where TEntity : BaseEntity
    {
        return base.Set<TEntity>();
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Configurations.Add(new AspNetRoleMap());
        modelBuilder.Configurations.Add(new AspNetUserClaimMap());
        modelBuilder.Configurations.Add(new AspNetUserLoginMap());
        modelBuilder.Configurations.Add(new AspNetUserMap());
        modelBuilder.Configurations.Add(new PersonMap());
    }

4 回答

  • 0

    您的上下文类必须从 IdentityDbContext 继承而不是DbContext . IdentityDbContext 包含 IdentityUser, IdentityRole, IdentityUserLogin, IdentityUserRole, IdentityUserClaim 的一些配置,它有 IDbSet UsersIDbSet Roles .

    public class MyContext : IdentityDbContext<IdentityUser or your own UserEntity>
    {
       .
       .
       .
    }
    
  • 0

    当然

    创建用户管理器的实例时,只需将用户存储与您自己的dbContext一起传递 .

    new UserManager<IdentityUser>(new UserStore<IdentityUser>(new MyDbContext()))
    
  • 1

    我的问题:我还需要手动创建实体类和 Map 吗?如何将我的表之间的关系映射到identityuser?

    不,您的所有Identity类都已映射 . 如果要添加与Identity的关系,可以像通常在上下文中的OnModelCreating方法那样处理您的Identity类(例如IdentityRole,IdentityUserRole,IdentityUser) .

    有关如何完成此操作的更多信息,请查看this article .

  • 0

    在EF 6.0中,更好的方法是使用两个单独的上下文,然后根据Multiple DB Contexts in the Same DB and Application in EF 6 and Code First Migrations使用相同的连接字符串和2个不同的迁移配置 .

相关问题