我可以指定实体框架code首先全局映射规则? [英] Can I specify global mapping rules in Entity Framework Code First?

查看:136
本文介绍了我可以指定实体框架code首先全局映射规则?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用实体框架code首先建立一个应用程序在ASP.NET MVC 4,为简单起见,我继承了将从都有一个GUID,一个dateCreated会一BaseEntity被存储在数据库中的所有车型一个LastEditDate和这样的其他有用的特性。现在,我知道我可以告诉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将属性为每个类型映射为你不'T让 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的一些映射也可以通过定制code第一约定解决:的http://romiller.com/2013/01/29/ef6-$c$c-first-configuring-unmapped-base-types/

这篇关于我可以指定实体框架code首先全局映射规则?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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