I started migrating from Asp.net MVC to Asp.Net MVC Core, I realized that some things are a little bit different than I expected. I'd like to know how I can set some propeties like I used to do in 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());
...
}
It seems I can't do it do using EF Core
protected override void OnModelCreating(ModelBuilder builder)
{
}
Does anyone knows how I can do that?
It is not working because you have to call this line for your entities first
var entityBuilder = modelBuilder.Entity<SomeEntity>();
Then do the following:
entityBuilder.Property(someEntity => someEntity.SomeProperty)
.HasColumnType("char")
.HasMaxLength(10)
.IsRequired();
Also have a look at IEntityTypeConfiguration<> it will help you to keep your DbContext clean. Within your DbContext OnModelCreating Method you will then just call
modelBuilder.ApplyConfiguration(new SomeEntityConfiguration());
Based on that you can also define a base class for common properties and create a base IEntityTypeConfiguration<> for common properties. Not much magic there but some things are just better defined explicit rather than implicit.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.