6

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?

ajr
  • 874
  • 2
  • 13
  • 29
  • 1
    http://stackoverflow.com/questions/26957519/ef-7-mapping-entitytypeconfiguration – L-Four Jan 18 '16 at 13:33
  • I recommend you to use `dnx ef dbcontext scaffold` to generate Model from the *existing* database (see [the answer](http://stackoverflow.com/a/34457974/315935) for details). You will get many very good examples how to use fluent API in EF7 if you would get enough complex database as the source. – Oleg Jan 18 '16 at 15:30

2 Answers2

7

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>());
}
Szer
  • 3,426
  • 3
  • 16
  • 36
1

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.

zackery.fix
  • 1,786
  • 2
  • 11
  • 20
  • Attributes will go away with EF7 – Szer Jan 18 '16 at 15:10
  • @Szer: source of your statement? Because I see that attributes/data annotations will be there (https://github.com/aspnet/EntityFramework/wiki/Roadmap) – L-Four Jan 18 '16 at 15:18
  • I was referring to .NET attributes, no EF data annotations. – zackery.fix Jan 18 '16 at 15:18
  • 1
    @L-Three didn't know they've changed their mind. I was sure that they going to remove Annotations and leave only code-first way to model relationships. – Szer Jan 18 '16 at 15:25