我可以在 Entity Framework Code First 中指定全局映射规则吗? [英] Can I specify global mapping rules in Entity Framework Code First?

查看:31
本文介绍了我可以在 Entity Framework Code First 中指定全局映射规则吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Entity Framework Code First 在 ASP.NET MVC 4 中构建应用程序,为简单起见,我将从具有 Guid、DateCreated、LastEditDate 的 BaseEntity 继承将存储在数据库中的所有模型以及其他类似的有用属性.现在,我知道我可以告诉 EF 像这样映射这些继承的属性:

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 that has a Guid, a DateCreated, a LastEditDate and a other useful properties like that. Now, I know that I can tell EF to map these inherited properties like so:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<User>().Map(m =>
    {
        m.MapInheritedProperties();
    });

    modelBuilder.Entity<Product>().Map(m =>
    {
        m.MapInheritedProperties();
    });            
}

不过,对每个项目都必须这样做似乎很愚蠢.有没有一种方法可以将此规则应用于所有实体?

It seems silly to have to do this for every item, though. Is there a way I can apply this rule to all entities in one?

推荐答案

在这种特定情况下没有必要进行全局映射,因为 EF 将映射每个单独类型的属性,只要您不这样做不要让 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.

但您的问题标题更笼统,是的,如果您通过 EntityTypeConfiguration 配置映射,则可以指定全局映射规则.它可能看起来像这样:

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<T> : EntityTypeConfiguration<T>
  where T : BaseEntity
{
  protected BaseMapping()
  {
    this.Map(m => m.MapInheritedProperties()); // OK, not necessary, but
                                               // just an example
  }
}

// Specific configurations
public class UserMapping : BaseMapping<User>
{ }

public class ProductMapping : BaseMapping<Product>
{ }

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

注意:

从实体框架 6 开始,其中一些映射也可以通过自定义代码优先约定来解决:http://romiller.com/2013/01/29/ef6-code-first-configuring-unmapped-base-types/

这篇关于我可以在 Entity Framework Code First 中指定全局映射规则吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆