【问题标题】:How can I avoid ASP.NET Identity from adding this extra field?如何避免 ASP.NET Identity 添加此额外字段?
【发布时间】:2014-12-04 01:26:27
【问题描述】:

我有一个带有 ASP.NET Identity 2.0 和 EF 6.1.1 的新 MVC5 项目。

我添加了自己的 ApplicationUser(基于内置 IdentityUser)。这就是我的 DbContext 的创建方式。

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public ApplicationDbContext()
        : base("DefaultConnection", throwIfV1Schema: false)
    {
    }

    public static ApplicationDbContext Create()
    {
        return new ApplicationDbContext();
    }
}

创建数据库后,我有像 AspNetUsers、AspNetUserRoles、AspNetUserClaims 和 AspNetUserLogins 这样的表。然后我添加了仅包含最基本语句的 OnModelCreating()。

 protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<IdentityUserLogin>().HasKey<string>(l => l.UserId);
        modelBuilder.Entity<IdentityUserRole>().HasKey(r => new { r.RoleId, r.UserId });
    }

添加 OnModelCreating() 后,身份表会自动重命名为 ApplicationUsers、IdentityUserRoles、IdentityUserClaims 和 IdentityUserLogins。这对我来说很好(而且我知道如何重命名它们)。

但我不喜欢的是:突然之间,IdentityUserRoles、IdentityUserClaims 和 IdentityUserLogins 有了一个名为“ApplicationUser_Id”的额外字段。原来的“AspNetXXX”表没有这样的字段。

这是为什么呢?为了避免这种情况,我能做些什么吗?

【问题讨论】:

    标签: ef-code-first asp.net-identity


    【解决方案1】:

    您需要致电base.OnModelCreatingOnModelCreatingIdentityDbContext 中还有许多额外的功能,如果不调用它,您可能会错过它们 - 表的默认名称就是其中之一。

    最好先调用它,然后再应用您自己的更改。

    【讨论】:

      【解决方案2】:

      正如Matt Lassam-Jones所提到的

      也为我工作,谢谢。

      public class NebulaContext : IdentityDbContext<ApplicationUser>
          {
              public NebulaContext()
                  : base("Name=MyEntity", throwIfV1Schema: false)
              {
      
              }
      
          protected override void OnModelCreating(DbModelBuilder modelBuilder)
                  {         
                      modelBuilder.Conventions.Remove<PluralizingTableNameConvention>(); //Optional
                      modelBuilder.Conventions.Remove<ManyToManyCascadeDeleteConvention>();//Optional
                      modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>(); //Optional
                      base.OnModelCreating(modelBuilder);
          }
      }
      

      【讨论】:

        猜你喜欢
        • 2018-06-14
        • 1970-01-01
        • 1970-01-01
        • 2013-03-22
        • 1970-01-01
        • 1970-01-01
        • 2012-01-26
        • 1970-01-01
        • 2015-08-26
        相关资源
        最近更新 更多