【问题标题】:EF4 CTP5 How To? Map an inherited Property to a field in a related tableEF4 CTP5 如何?将继承的属性映射到相关表中的字段
【发布时间】:2011-11-06 16:09:44
【问题描述】:

我使用 Table Per Hierarchy (TPH) 定义了一个名为变量的实体和派生类。基类“变量”包含一组 PropertyValue:

private ICollection<PropertyValue> propertyValues;

public const string DiscriminatorColumn = "Discriminator";
public const string Table = "Variables";

public VariableType VariableType { get; set; }
public string Name { get; set; }

[NotMapped]
public string Discriminator { get; set; }

public virtual ICollection<PropertyValue> PropertyValues
{
    get { return this.propertyValues ?? (this.propertyValues = new ObservableCollection<PropertyValue>()); }
    set { SetProperty(ref this.propertyValues, value, () => PropertyValues); }
}

现在,我想派生一个 SpecialVariable 类(或多个),它定义了一些应该映射到 PropertyValues(表)中的条目的 SpecialProperties(例如 HighLimit)。

public class MySpecialVariabe : Variable
{
    public double HighLimit { get; set; }
}

我的 OnModelCreating 函数目前看起来像这样:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Variable>().HasKey(x => new { x.Id });

    modelBuilder.Entity<Variable>()
        .Map<MySpecialVariabe>(m => m.Requires(Variable.DiscriminatorColumn).HasValue(typeof(MySpecialVariabe).Name))
        .Map<MySpecialVariabe2>(m => m.Requires(Variable.DiscriminatorColumn).HasValue(typeof(MySpecialVariabe2).Name)).ToTable(Variable.Table);
}

谁能给我一些提示如何实现这一点,而无需在派生类中编写大量难看的代码。 (性能没那么重要。)

最好的问候,

克里斯

【问题讨论】:

    标签: c# entity-framework-4 mapping tph


    【解决方案1】:

    您不能将属性映射到记录。我就是这样理解你的问题的。您有一些 PropertyValues 表,它很可能是一些键/值对,并且您希望将实体属性作为记录(数据)映射到该表。这不是 EF 为您做的事情。您必须提供未映射的属性,这些属性将与 propertyValues 集合中的正确记录一起使用。

    类似:

    [NotMapped]
    public double HighLimit
    {
      get
      {
        var current = propertyValues.SingleOrDefault(p => p.Key == "HighLimit");
        return current != null ? current.Value : 0.0;
      }
      set 
      {
        var current = propertyValues.SingleOrDefault(p => p.Key == "HighLimit");
        if (current != null)
        {
          current.Value = value;
        }
        else
        {
          propertyValues.Add(new PropertyValue { Key = "HighLimit", Value = value });
        }
      }
    }
    

    这种方法的问题是您不能在 Linq-to-entities 查询中使用 HighLimit - 您必须始终使用 PropertyValues。

    此外,EF 中的 TPH 要求派生实体 (MySpecialVariable) 的属性映射到与父实体 (Variable) 相同的表。您不能将派生实体的属性映射到存储在其他表 (PropertyValues) 中的数据。

    【讨论】:

    • 嗨,Ladislav,你的回答是我所期望的,也是我在想的,但希望最后死去。我不喜欢这种方法的是每个属性都有太多代码。谢谢,最好的问候,克里斯
    猜你喜欢
    • 2011-07-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-01
    • 1970-01-01
    相关资源
    最近更新 更多