【问题标题】:Can I use the same dbcontext for asp identity我可以对 asp 身份使用相同的 dbcontext
【发布时间】:2014-09-02 21:33:39
【问题描述】:

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

编辑

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

我的问题:

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

这是我当前的 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());
    }

【问题讨论】:

    标签: c# asp.net-mvc entity-framework ef-code-first asp.net-identity


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      当然

      当您创建用户管理器的实例时,只需传递用户存储以及您自己的 dbContext。

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

      【讨论】:

      • 身份使用IdentityDbContext。使用普通的 DbContext 有什么缺点吗?
      【解决方案3】:

      我的问题:

      我还需要手动创建实体类和映射吗?我如何映射 我的表与身份用户之间的关系?

      不,您的所有身份类都已映射。如果你想为你的身份添加关系,你可以像往常一样在 OnModelCreating 方法中在上下文本身引用你的身份类(例如 IdentityRole、IdentityUserRole、IdentityUser)。

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

      【讨论】:

      【解决方案4】:

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

      【讨论】:

        猜你喜欢
        • 2013-11-28
        • 1970-01-01
        • 1970-01-01
        • 2017-05-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多