Entity-framework-7 Organization of Fluent API configurations in a separate class

I know how to organize flexible API configurations into a separate class on EF6, but how is this achieved with EF7?

Here is an example of how to do this with EF6:

ModelConfigurations.cs

public class ModelConfigurations : EntityTypeConfiguration<Blog> { ToTable("tbl_Blog"); HasKey(c => c.Id); // etc.. } 

and call it from OnModelCreating ()

  protected override void OnModelCreating(DbModelbuilder modelBuilder) { modelBuilder.Configurations.Add(new ModelConfigurations()); // etc... } 

In EF7, I can not solve EntityTypeConfiguration? What is the correct way to implement free API calls from a separate class?

+6
source share
2 answers

Try the following:

 public class BlogConfig { public BlogConfig(EntityTypeBuilder<Blog> entityBuilder) { entityBuilder.HasKey(x => x.Id); // etc.. } } protected override void OnModelCreating(ModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); new BlogConfig(modelBuilder.Entity<Blog>()); } 
+5
source

What I usually do for all my entity classes is a static method that is called from my OnModelCreating method in my context implementation:

 public class EntityPOCO { public int Id { get; set; } public static OnModelCreating(DbModelBuilder builder) { builder.HasKey<EntityPOCO>(x => x.Id); } } ... public class EntityContext : DbContext { public DbSet<EntityPOCO> EntityPOCOs { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); EntityPOCO.OnModelCreating(modelBuilder); } } 

Going further, you can even automate the process and generate a context class on the fly using attributes. Thus, you only need to deal with POCOs and never touch the context.

+1
source

All Articles