I\'m building an app in ASP.NET MVC 4 using Entity Framework Code First, and for simplicity I\'m inheriting all models that will be stored in the database from a BaseEntity
It has been stated correctly that it's not necessary to do global mapping in this specific case, because EF will map the properties for each individual type as long as you don't make BaseEntity part of the model.
But your question title is stated more generally and yes, it is possible to specify global mapping rules if you configure the mappings by EntityTypeConfigurations. It could look like this:
// Base configuration.
public abstract class BaseMapping : EntityTypeConfiguration
where T : BaseEntity
{
protected BaseMapping()
{
this.Map(m => m.MapInheritedProperties()); // OK, not necessary, but
// just an example
}
}
// Specific configurations
public class UserMapping : BaseMapping
{ }
public class ProductMapping : BaseMapping
{ }
public class TempModelsContext : DbContext
{
// Add the configurations to the model builder.
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Configurations.Add(new UserMapping());
modelBuilder.Configurations.Add(new ProductMapping());
}
// DbSets
...
}
As of Entity Framework 6 some of these mappings can also be solved by custom code first conventions: http://romiller.com/2013/01/29/ef6-code-first-configuring-unmapped-base-types/