In EF 6 we could directly pass EntityTypeConfiguration to model builder to build maps and keep our configuration class separate from context without being too verbose in code.
Have they removed those maps in EF core. Is there a way to add configuration without doing it in model builder for every class?
The best way is to keep the configuration code away from the OnModelCreating
method. So you can do something like:
Create a class where you will store the actual configuration:
public class ApplicationUserConfiguration
{
public ApplicationUserConfiguration(EntityTypeBuilder<ApplicationUser> entity)
{
// Here you have all the good stuff
entity.ToTable("user", "identity");
entity.Property(p => p.Id)
.HasColumnName("id);
// And so on ....
}
}
And into your OnModelCreating
instantiate the new created class and pass the correct entity:
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
// Your custom configs here
new ApplicationUserConfiguration(builder.Entity<ApplicationUser>());
}
Is clean and a simple way to achieve the goal.
EntityFrameworkCore2.0 has a IEntityTypeConfiguration<TEntity>
which can be used as:
class ApplicationUserMap : IEntityTypeConfiguration<ApplicationUser>
{
public void Configure(EntityTypeBuilder<Customer> builder)
{
builder.ToTable("user", "identity");
builder.Property(p => p.Id)
.HasColumnName("id");
...
}
}
...
// OnModelCreating
modelBuilder.ApplyConfiguration(new ApplicationUserMap());