我开始从Asp.net MVC迁移到Asp.Net MVC Core,我意识到有些事情与我预期的有点不同。 我想知道如何设置一些像我以前在EF 6中所做的那样的事情
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
modelBuilder.Conventions.Remove<ManyToManyCascadeDeleteConvention>();
modelBuilder.Properties<string>().Configure(p => p.HasColumnType("varchar"));
modelBuilder.Properties<string>().Configure(p => p.HasMaxLength(100));
modelBuilder.Properties().Where(x => x.Name == "Active").Configure(x => x.HasColumnType("char").HasMaxLength(1).IsRequired());
modelBuilder.Properties().Where(x => x.Name == "Excluded").Configure(x => x.HasColumnType("char").HasMaxLength(1).IsRequired());
modelBuilder.Properties().Where(x => x.Name == "RegisterDate").Configure(x => x.IsRequired());
modelBuilder.Properties().Where(x => x.Name == "ChangeDate").Configure(x => x.IsRequired());
...
}
使用EF Core似乎无法做到这一点
protected override void OnModelCreating(ModelBuilder builder)
{
}
有谁知道我该怎么做?
答案 0 :(得分:1)
它无法正常工作,因为您必须先为您的实体调用此行
var entityBuilder = modelBuilder.Entity<SomeEntity>();
然后执行以下操作:
entityBuilder.Property(someEntity => someEntity.SomeProperty)
.HasColumnType("char")
.HasMaxLength(10)
.IsRequired();
另请查看IEntityTypeConfiguration<>它可以帮助您保持DbContext清洁。在你的DbContext OnModelCreating方法中,你只需要调用
modelBuilder.ApplyConfiguration(new SomeEntityConfiguration());
基于此,您还可以为公共属性定义基类并创建基本IEntityTypeConfiguration&lt;&gt;对于共同的属性。那里没什么神奇之处,但有些事情只是更明确地定义而非隐含。