Entity Type Configuration for EF7
Hello there.
I would like to share my approach to use something like EntityTypeConfiguration but for EF7.
I'm working on two projects that are equal in its bases and i wanna be able to configure, for example, Identity tables and share that code between projects.
So, i wrote the code bellow to be the primary thought:
public class EntityBuilder
{
public virtual ModelBuilder Build(ModelBuilder modelBuilder) => modelBuilder;
}
public class IdentityEntityBuilder : EntityBuilder
{
public override ModelBuilder Build(ModelBuilder modelBuilder)
{
modelBuilder
.Entity<Role>(b => b.ToTable("Role"))
.Entity<IdentityRoleClaim<int>>(b => b.ToTable("RoleClaim"))
.Entity<User>(b => b.ToTable("User"))
.Entity<IdentityUserClaim<int>>(b => b.ToTable("UserClaim"))
.Entity<IdentityUserLogin<int>>(b => b.ToTable("UserLogin"))
.Entity<IdentityUserRole<int>>(b => b.ToTable("UserRole"))
;
return modelBuilder;
}
}
public static class ModelBuilderExtensions
{
public static ModelBuilder EntityBuilder<TEntityBuilder>(this ModelBuilder modelBuilder) where TEntityBuilder : EntityBuilder, new()
=> new TEntityBuilder().Build(modelBuilder);
}
public class Context : IdentityDbContext<User, Role, int>
{
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
builder
.EntityBuilder<IdentityEntityBuilder>()
.Entity<X>()
.Entity<Y>()
.Entity<Z>();
}
}
I did some tests and it's working well for my needs.
What do you think about this approach?
This looks totally fine, there are lots of different ways to factor the code. We already have https://github.com/aspnet/EntityFramework/issues/2805 tracking implementing something like EntityTypeConfiguration