efcore icon indicating copy to clipboard operation
efcore copied to clipboard

Entity Type Configuration for EF7

Open dnlruzzo opened this issue 10 years ago • 1 comments

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?

dnlruzzo avatar Dec 29 '15 17:12 dnlruzzo

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 in EF7 - so I'm going to close this one out since there isn't really anything actionable from a bug/enhancement point of view.

rowanmiller avatar Dec 29 '15 19:12 rowanmiller