【问题标题】:New inherited class gets its property name renamed on migration with EF Code First新继承的类在迁移时使用 EF Code First 重命名其属性名称
【发布时间】:2015-12-08 11:44:10
【问题描述】:

我使用 Entity Framework Code First 和继承来定义我的类,每个类都实现一个包含所有它们都应该具有的公共属性的抽象类。

我想在批处理中添加一个新的时遇到了问题。所有继承的类都具有具有不同类型的通用名称的属性,但在最后一个类中,属性也具有相同的类型。

public abstract class ProductProperty
{
    public string CommonProp { get; set; }
}


public class IntegerProperty : ProductProperty
{
    [Required]
    public int Value { get; set; }
}

public class StringProperty : ProductProperty
{
    [Required]
    public string Value { get; set; }
}

public class DoubleProperty : ProductProperty
{
    [Required]
    public double Value { get; set; }
}

到目前为止,一切都很好。当我添加另一个具有整数值属性的值时,代码优先迁移是通过移动 SQL 表上现有的值列来创建的,而不是创建新的值列,这当然会导致问题,因为我已经在属性表中有数据。

public class IntWithUnitProperty : ProductProperty
{
    [Required]
    public int Value { get; set; }

    public string Unit { get; set; }
}

RenameColumn(table: "dbo.ProductProperties", name: "Value1", newName: "Value2");
RenameColumn(table: "dbo.ProductProperties", name: "Value2", newName: "Value3");
AlterColumn("dbo.ProductProperties", "Value1", c => c.Int());
AlterColumn("dbo.ProductProperties", "Value2", c => c.String());

很明显这在多个方面都是错误的,但我已经尝试更新数据库:

错误:新名称“Value2”已用作 COLUMN 名称,并且 会导致不允许的重复。

从这种行为中,我了解到 EF 开始按类名顺序给出名称和后缀:

  1. 双精度值
  2. Int 的 Value1
  3. 字符串的Value2

当我尝试将另一个名称以 Int... 开头的类添加到批处理中时,它会尝试将其放在 Value1 之后。

问题是,带有数字后缀的列名指向在 EF 中映射的具有相同继承类名称的属性?

也许我可以告诉 EF 在 SQL 中添加一个新列并指向正确的类,而不是试图操纵现有的类。

【问题讨论】:

    标签: c# entity-framework inheritance entity-framework-6


    【解决方案1】:

    我认为您最好使用数据注释明确命名您的 Value 列,而不是冒着在迁移期间重新分配它们的风险。例如:

    public class IntegerProperty : ProductProperty
    {
        [Required]
        [Column("Value1")]
        public int Value { get; set; }
    }
    
    public class StringProperty : ProductProperty
    {
        [Required]
        [Column("Value2")]
        public string Value { get; set; }
    }
    

    等等。

    或者,您可以使用每个类型的表 (TPT) 而不是默认的每个层次结构的表 (TPH),这样每个子类都有自己的表,因此 Value 将始终称为 Value。示例:http://weblogs.asp.net/manavi/inheritance-mapping-strategies-with-entity-framework-code-first-ctp5-part-2-table-per-type-tpt

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-04-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多