Define default values using EF Core - OnModelCreating

asp.net-core asp.net-core-mvc c# ef-core-2.0 entity-framework-core

Question

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?

1
1
8/20/2019 4:45:19 PM

Popular Answer

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.

1
2/19/2018 10:55:46 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow