实体框架 6 &TPH继承:默认将同名属性映射到同一列

Entity Framework 6 amp; TPH inheritance: Map properties with the same name to same column by default(实体框架 6 amp;TPH继承:默认将同名属性映射到同一列)
本文介绍了实体框架 6 &TPH继承:默认将同名属性映射到同一列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从 EF6 开始,可以在使用 Table Per Hierarchy 继承配置实体映射时执行以下操作:

As of EF6 it is possible to do something like this when configuring Entity mappings using Table Per Hierarchy inheritance:

public class MyContext : DbContext 
{
    public DbSet<Device> Devices { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<ABatteryPoweredDevice>().Property(c => c.BatteryLevel).HasColumnName("BatteryLevel");
        modelBuilder.Entity<ADifferentBatteryPoweredDevice>().Property(c => c.BatteryLevel).HasColumnName("BatteryLevel");
    }
}

BatteryLevel 不是 Device 基类的一部分 - 它是实现接口契约的派生类的属性.

BatteryLevel is not part of the Device base class- it is a property of the derived classes implemented to fulfill an interface contract.

是否可以将此设置为默认行为,而不必为每个派生类添加新映射?

Is it possible to make this the default behavior as opposed to having to add a new mapping for each derived class?

推荐答案

使用 自定义代码优先约定,从 EF6 开始提供,来解决这个问题:

Used Custom Code First Conventions, which are available from EF6 onwards, to sort this out:

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        //your code before
        modelBuilder.Properties().Configure(prop => prop.HasColumnName(prop.ClrPropertyInfo.Name));
        //your code after
    }

这会将不同派生类型中具有相同名称的属性映射到同一个表列,而无需像问题中提到的那样显式调用.

This maps properties with the same name in different derived types to the same table column without explicit calls like those mentioned in the question.

这篇关于实体框架 6 &amp;TPH继承:默认将同名属性映射到同一列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
quot;Overflowquot; compiler error with -9223372036854775808L(编译器错误-9223372036854775808L(Q;溢出Q))
Visual Studio 2010 ReportViewer Assembly References(Visual Studio 2010 ReportViewer程序集引用)
Weird behaviour when I open a reportviewer in WPF(在WPF中打开报表查看器时出现奇怪的行为)
how do i pass parameters to aspnet reportviewer(如何将参数传递给aspnet report查看器)