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?
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>());
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With