Can I specify global mapping rules in Entity Framework Code First?

前端 未结 2 1107
不知归路
不知归路 2020-11-27 08:27

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

2条回答
  •  盖世英雄少女心
    2020-11-27 09:26

    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
      ...
    }
    

    NOTE:

    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/

提交回复
热议问题