Asp.net mvc 向DbContext添加新实体

Asp.net mvc 向DbContext添加新实体,asp.net-mvc,entity-framework,ef-code-first,asp.net-identity,entity-framework-migrations,Asp.net Mvc,Entity Framework,Ef Code First,Asp.net Identity,Entity Framework Migrations,我使用带有标识的ASP.NET内核,并希望扩展默认的Db上下文。如果要添加非链接表,只需添加一个新类: public partial class Table1 { public int Id { get; set; } public string Txt { get; set; } } 并扩展我的ApplicationDbContext: public class ApplicationDbContext : IdentityDbContext<ApplicationUs

我使用带有标识的ASP.NET内核,并希望扩展默认的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);
        });
    }
}
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创建的)。如何正确执行此操作?

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

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

  • 毫无疑问,
    Users
    ApplicationUser
    ,以及数据库表
    dbo.Users
    dbo.AspNetUsers
    之间会存在混淆

  • 通常,您应该以单数时态命名实体,即
    User
    ,而不是
    Users
    。这种约定有很多原因,但只需说一句,对于单数事物,坚持使用单数时态;对于复数事物,坚持使用复数时态,只会使代码更好、更可读。例如,类型为
    ICollection
    的属性将命名为
    Users
    ,因为它由许多
    User
    实例组成

  • 你所做的完全没有必要。Identity存在的全部原因是成员身份(ASP.NET以前使用的身份验证和授权框架)不允许您扩展所涉及的类型。Identity改变了所有这些,并且在各个方面都是100%可扩展的。您拥有对框架中涉及的所有实体的完全访问权,并且可以添加到这些实体并从中派生。如果要为系统中的“用户”添加其他属性,只需将它们直接添加到
    ApplicationUser
    类中即可


  • 我必须添加它,因为它已经完成的项目,基于会员资格ProviderIdentity和会员资格是相互排斥的。要么升级到Identity,要么继续使用会员资格。您绝对不应该试图同时使用这两种方法。