Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity-framework-7 Organizing Fluent API configurations into a separate class

I'm familiar how to organize the fluent API configurations into a separate class on EF6, but how is this achieved with EF7?

Here is an example how to do it with EF6:

ModelConfigurations.cs

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

and to call it from OnModelCreating()

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

On EF7 I cant resolve the EntityTypeConfiguration? What is the correct way to implement fluent API calls from a separate class?

like image 389
ajr Avatar asked Jan 18 '16 13:01

ajr


2 Answers

Try this:

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>());
}
like image 118
Szer Avatar answered Sep 24 '22 13:09

Szer


What I typically do for all my entity classes is provide a static method that gets 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 a step further, you could even automate the process and generate the context class on the fly using attributes. This way you only have to deal with the POCOs and never touch the context.

like image 35
zackery.fix Avatar answered Sep 26 '22 13:09

zackery.fix