Model configuration: Entity type configuration can be factored into a class
Edited by @rowanmiller Oct-13-2016
EntityTypeConfiguration<T> is a feature in EF6.x that allows you to encapsulate the configuration for an entity type in a class.
Here is some code you can use to enable the pattern until we add support in EF Core.
using Microsoft.EntityFrameworkCore.Metadata.Builders;
namespace Microsoft.EntityFrameworkCore
{
public abstract class EntityTypeConfiguration<TEntity>
where TEntity : class
{
public abstract void Map(EntityTypeBuilder<TEntity> builder);
}
public static class ModelBuilderExtensions
{
public static void AddConfiguration<TEntity>(this ModelBuilder modelBuilder, EntityTypeConfiguration<TEntity> configuration)
where TEntity : class
{
configuration.Map(modelBuilder.Entity<TEntity>());
}
}
}
And here is a sample application that uses these types:
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
namespace Demo
{
class Program
{
static void Main(string[] args)
{
using (var db = new BloggingContext())
{
db.Database.EnsureCreated();
}
}
}
public class BloggingContext : DbContext
{
public DbSet<Blog> Blogs { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer(@"Server=(localdb)\mssqllocaldb;Database=Demo;Trusted_Connection=True;");
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.AddConfiguration(new BlogMap());
}
}
public class Blog
{
public int BlogId { get; set; }
public string Name { get; set; }
public string Url { get; set; }
}
public class BlogMap : EntityTypeConfiguration<Blog>
{
public override void Map(EntityTypeBuilder<Blog> builder)
{
builder.ToTable("tbl_blogs");
builder.Property(b => b.Name)
.IsRequired()
.HasMaxLength(200);
builder.Property(b => b.Url)
.IsRequired()
.HasMaxLength(500);
builder.HasIndex(b => b.Url);
}
}
}
You can configure the mapping by overriding OnModelCreating in your derived DbContext
Is there a specific thing you aren't able to configure?
So if we have complex mappings, we just need to factor out into our own static classes and call them from OnModelCreating. This will need to suffice for the primary use case for EntityTypeConfiguration in EF6.
There are several ways of factoring OnModelCreating.
For example you can turn
public override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Chassis>(b =>
{
b.Key(c => c.TeamId);
b.Property(e => e.Version)
.ValueGeneratedOnAddOrUpdate()
.ConcurrencyToken();
});
}
into
public override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Chassis>(ConfigureChassis);
}
private static void ConfigureChassis(EntityTypeBuilder<Chassis> b)
{
b.Key(c => c.TeamId);
b.Property(e => e.Version)
.ValueGeneratedOnAddOrUpdate()
.ConcurrencyToken();
}
or
public override void OnModelCreating(ModelBuilder modelBuilder)
{
ConfigureChassis(modelBuilder);
}
private static void ConfigureChassis(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Chassis>(b =>
{
b.Key(c => c.TeamId);
b.Property(e => e.Version)
.ValueGeneratedOnAddOrUpdate()
.ConcurrencyToken();
});
}
It would be really great to have something like EntityTypeConfiguration
Reopening so that we can triage this... we should consider enabling the same pattern we had in EF6. It's trivial to implement it yourself... but it is a nice piece of sugar that we've seen numerous people use.
I'm glad I'm not the only one. I rely on it heavily.
I've actually started a solution that I can probably contribute back.
Moving to backlog since it's not critical for our initial release (it's very easy to quickly implement this yourself without needing to modify EF code). That said, we do want to implement it and we would accept a PR for it.
@mmillican Do you have anything available already? I require the functionality of being able to specify entity type configurations, too. However, I won't have access to a concrete DbContext implementation to access OnModelCreating (this issue has been persistent throughout EF releases, requiring proxying to get around), as the DbContext is generated on-the-fly with assembly scanning. I would implement an IModelSource, but individual implementations of providers have their own modelsource which they request on model creation. One of the solutions I can see, is adding an two interfaces:
public interface IModelBuilderContributor
{
void Contribute(ModelBuilder modelBuilder);
}
public interface IModelBuilderContributorSource
{
IEnumerable<IModelBuilderContributor> GetContributors([NotNull] DbContext context);
}
and extend parameters of IModelSource => GetModel() and ModelSource => CreateModel() with [CanBeNull] IModelBuilderContributorSource value
Between FindSets() and OnModelCreating() add
if (contributorSource != null)
ContributeToModelBuilder(modelBuilder, contributorSource.GetContributors(context));
protected virtual void ContributeToModelBuilder(ModelBuilder modelBuilder, IEnumerable<IModelBuilderContributor> getContributors)
{
foreach(var contributor in getContributors)
contributor.Contribute(modelBuilder);
}
finally add to DbContextServices constructor private variable assignment
_modelBuilderContributorSource =
new LazyRef<IModelBuilderContributorSource>(
() => _provider.GetRequiredService<IModelBuilderContributorSource>());
This would give "infinite extension points!", as contributors would come through DbContext's own serviceprovider, have the capability for DI, and would allow any arbitrary additional extension points (such as EntityTypeConfigurationContributor). All providers would therefore also have support for it.
If this is something that would be even wildly acceptable in EF7 (rather than hardwiring the responsibility of adding type configurations in OnModelCreating override), and is not already worked on, I'm more than willing to implement and PR.
@Grinderofl - I haven’t yet, unfortunately; I got tied up in projects. It is still on my list however.
My use case is similar to yours, in that I use assembly scanning to add types to the context. This is extremely useful for large applications as well as “plugin” style applications.
I think I follow what you are saying with your ideas, and they make sense. My idea was to essentially replicate the EntityTypeConfiguration<T> functionality.
Okay, I'll attempt to implement it and pr, got some rough stubs in place now.
#2992 describes a mechanism that could be used to implement this.
This is still required, unfortunately due to time constraints I had to go ahead and implement the ability to configure dbcontext programmatically via https://github.com/Grinderofl/FluentModelBuilder instead of PRing, though truly, all that is needed, is to expose ModelBuilder somewhere outside of DbContext.OnModelCreating().
Removing EntityTypeConfiguration<T> and modelBuilder.Configurations.AddFromAssembly is a step backwards. I had to implement modelBuilder.Configurations.AddFromAssembly on my own since EF Code First CPT3 to comply with the open/closed principle. Finally in 6 it was part of the flow and now in EF7 all the bits are gone. #IMHO
@valmont EF Core is still trying to focus on simplicity first, which means that there's a mechanism to support any kind of model customization - IModelCustomizer (implement/override ModelCustomizer, replace in services after AddEntityFramework())
I've written a library to make that a bit easier if you are interested.
https://github.com/Grinderofl/FluentModelBuilder
public interface IEntityMappingConfiguration
{
void Map(ModelBuilder b);
}
public interface IEntityMappingConfiguration<T> : IEntityMappingConfiguration where T : class
{
void Map(EntityTypeBuilder<T> builder);
}
public abstract class EntityMappingConfiguration<T> : IEntityMappingConfiguration<T> where T : class
{
public abstract void Map(EntityTypeBuilder<T> b);
public void Map(ModelBuilder b)
{
Map(b.Entity<T>());
}
}
public static class ModelBuilderExtenions
{
private static IEnumerable<Type> GetMappingTypes(this Assembly assembly, Type mappingInterface)
{
return assembly.GetTypes().Where(x => !x.IsAbstract && x.GetInterfaces().Any(y => y.GetTypeInfo().IsGenericType && y.GetGenericTypeDefinition() == mappingInterface));
}
public static void AddEntityConfigurationsFromAssembly(this ModelBuilder modelBuilder, Assembly assembly)
{
var mappingTypes = assembly.GetMappingTypes(typeof (IEntityMappingConfiguration<>));
foreach (var config in mappingTypes.Select(Activator.CreateInstance).Cast<IEntityMappingConfiguration>())
{
config.Map(modelBuilder);
}
}
}
Use:
public class PersonConfiguration : EntityMappingConfiguration<Person>
{
public override void Map(EntityTypeBuilder<Person> b)
{
b.ToTable("Person", "HumanResources")
.HasKey(p => p.PersonID);
b.Property(p => p.FirstName).HasMaxLength(50).IsRequired();
b.Property(p => p.MiddleName).HasMaxLength(50);
b.Property(p => p.LastName).HasMaxLength(50).IsRequired();
}
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.AddEntityConfigurationsFromAssembly(GetType().Assembly);
}
So is EntityTypeConfiguration class (and modelBuilder.Configurations.Add mechanism) going to be implemented?
@freerider7777 I don't think EF team has this as a priority in their sights right now. In the meanwhile, may I point you towards the release of https://github.com/Grinderofl/FluentModelBuilder which does what you are looking for and more.
I think we will probably do this, or something like it, but it is lower priority than some of the other features EF Core is missing at the moment.
In case you want this with .NET Core:
Make sure you have this in your project.json:
"System.Reflection.TypeExtensions": "4.1.0",
And modify the code to use:
using System;
using System.Collections.Generic;
using System.Reflection;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using System.Linq;
public interface IEntityMappingConfiguration
{
void Map(ModelBuilder b);
}
public interface IEntityMappingConfiguration<T> : IEntityMappingConfiguration where T : class
{
void Map(EntityTypeBuilder<T> builder);
}
public abstract class EntityMappingConfiguration<T> : IEntityMappingConfiguration<T> where T : class
{
public abstract void Map(EntityTypeBuilder<T> b);
public void Map(ModelBuilder b)
{
Map(b.Entity<T>());
}
}
public static class ModelBuilderExtenions
{
private static IEnumerable<Type> GetMappingTypes(this Assembly assembly, Type mappingInterface)
{
return assembly
.GetTypes()
.Where(x =>
!x.GetTypeInfo().IsAbstract &&
x.GetInterfaces().Any(y => y.GetTypeInfo().IsGenericType && y.GetGenericTypeDefinition() == mappingInterface));
}
public static void AddEntityConfigurationsFromAssembly(this ModelBuilder modelBuilder, Assembly assembly)
{
var mappingTypes = assembly.GetMappingTypes(typeof(IEntityMappingConfiguration<>));
foreach (var config in mappingTypes.Select(Activator.CreateInstance).Cast<IEntityMappingConfiguration>())
config.Map(modelBuilder);
}
}
and
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.AddEntityConfigurationsFromAssembly(GetType().GetTypeInfo().Assembly);
}
Hi Friends,
I would like to map this Separate EntityMap in ModelBuilder, Could you please help me how we cn do this. I am using EntityFrameworkCore.
public class EnquiryMap : EntityTypeConfiguration<Enquiry>
{
public const string TableName = "Enquiry";
public EnquiryMap()
{
ToTable(TableName);
Property(x => x.Key);
Property(x => x.ApplicationNumber);
}
}
public class DbAccessContext :DbContext
{
public DbSet<Enquiry> Enquiries { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
//?????????????
//modelBuilder.Entity<>
//.RegisterEntityMapping<Enquiry, EnquiryMap>();
}
}