将新实体添加到DbContext

时间:2017-04-18 17:51:04

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

我使用带有Identity的ASP.NET Core并希望扩展默认的Db上下文。如果我想添加未链接的表,我只需添加一个新类:

public partial class Table1
{
    public int Id { get; set; }
    public string Txt { get; set; }
}

并扩展我的ApplicationDbContext:

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
        : base(options)
    {
    }

    public virtual DbSet<Table1> Table1 { get; set; }

    protected override void OnModelCreating(ModelBuilder builder)
    {
        base.OnModelCreating(builder);
        // Customize the ASP.NET Identity model and override the defaults if needed.
        // For example, you can rename the ASP.NET Identity table names and more.
        // Add your customizations after calling base.OnModelCreating(builder);

        builder.Entity<Table1>(entity =>
        {
            entity.ToTable("Table_1");

            entity.Property(e => e.Id).HasColumnName("ID");

            entity.Property(e => e.Txt)
                .IsRequired()
                .HasMaxLength(50);
        });
    }
}

然后创建迁移并更新db。有用。但是,如果我想添加一个新表,该表链接到IdentityDbContext的表:

public partial class Users
{
    public int Id { get; set; }
    public string UserId { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }

    public virtual AspNetUser User { get; set; }
}

当然,AspNetUser类不存在(它由IdentityDbContext创建,据我所知)。如何正确地做到这一点?

1 个答案:

答案 0 :(得分:1)

该类很可能被命名为ApplicationUser(默认值)。表示此实体的表是dbo.AspNetUsers,但这是由Identity设置的,与类名无关。

但是,FWIW,创建Users实体是一个坏主意,原因有很多:

  1. 毫无疑问,UsersApplicationUser以及数据库表dbo.Usersdbo.AspNetUsers之间会产生混淆。

  2. 通常,您应该以单数形式命名实体,即User,而不是Users。这个约定有很多原因,但足以说明,它只是让你的代码更好,更易读,坚持奇异事物的单数时态和复数事物的复数时态。例如,ICollection<User>类型的属性将被命名为Users,因为它由许多User个实例组成。

  3. 您所做的事情完全没必要。身份存在的全部原因是成员资格(ASP.NET采用的先前身份验证和授权框架)不允许您扩展所涉及的类型。身份会改变这一切,并且在各方面都是100%可扩展的。您可以完全访问框架中涉及的所有实体,您可以添加它们并从中派生。如果您想为&#34;用户添加其他属性&#34;在您的系统中,只需将它们直接添加到ApplicationUser类。

相关问题