Entity Framework core configurations

asp.net-core entity-framework entity-framework-core

Question

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?

1
12
3/28/2017 1:12:10 PM

Accepted Answer

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.

12
3/28/2017 4:16:17 PM

Popular Answer

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());


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