Asp.net mvc 向DbContext添加新实体
我使用带有标识的ASP.NET内核,并希望扩展默认的Db上下文。如果要添加非链接表,只需添加一个新类: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
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
实例组成ApplicationUser
类中即可我必须添加它,因为它已经完成的项目,基于会员资格ProviderIdentity和会员资格是相互排斥的。要么升级到Identity,要么继续使用会员资格。您绝对不应该试图同时使用这两种方法。