是否可以在EF 4.1中使用复杂类型的继承TPH?
[ComplexType]
public class Unit
{
public double Value { get; set; }
public Unit() { }
public Unit(double Value)
{
this.Value = Value;
}
}
public class Celsius: Unit
{
public Celsius(double Value) : base (Value) { }
public static explicit operator Kelvin(Celsius c)
{
return new Kelvin(c.Degrees + 273.16d);
}
[NotMapped]
public double Degrees
{
get { return this.Value; }
}
}
我在这个班级协会中一对一使用 当我调用()时,SaveChanges()会引发异常
public class Measurement
{
[Key,
Column("Id"),
DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public long Id { get; set; }
public DateTime MTime { get; set; }
public Unit Value { get; set; }
}
和上下文:
class TestContext : DbContext
{
public DbSet<Measurement> Measurements { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
try
{
modelBuilder.ComplexType<Unit>().Property(u => u.Value).HasColumnName("Value");
modelBuilder.Entity<Unit>()
.Map<Celsius>(m => m.Requires("TypeName").HasValue("Celsius"))
.Map<Kelvin>(m => m.Requires("TypeName").HasValue("Kelvin"));
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
}
是否可以首先在FE 4.1代码中使用具有继承one-table-hierarchy的复杂类型?
答案 0 :(得分:0)
好的,我在EF 5测试版中测试过,但我认为这应该是一样的。这是一种解决方法,但您可以使用它。当这是一个复杂类型时,鉴别器部分似乎不起作用,所以我在相应的构造函数中初始化它。
我有这个并且它有效:
public class Measurement
{
[Key,
Column("Id"),
DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public long Id { get; set; }
public DateTime MTime { get; set; }
public virtual Unit Value { get; set; }
}
[ComplexType]
public class Unit
{
protected Unit()
{
}
protected Unit(double value)
{
Value = value;
}
[Column("Value")]
public double Value { get; set; }
[Column("TypeName")]
public string TypeName { get; set; }
}
public class Celsius : Unit
{
public Celsius(double value) : base(value)
{
TypeName = "Celsius";
}
public static explicit operator Kelvin(Celsius c)
{
return new Kelvin(c.Degrees + 273.16d);
}
public double Degrees
{
get { return this.Value; }
}
}
public class Kelvin : Unit
{
public Kelvin(double value) : base(value)
{
TypeName = "Kelvin";
}
public static explicit operator Celsius(Kelvin k)
{
return new Celsius(k.Degrees - 273.16d);
}
public double Degrees
{
get { return this.Value; }
}
}
class TestContext : DbContext
{
public DbSet<Measurement> Measurements { get; set; }
}
以下是迁移代码,以查看在DB中生成的内容:
public partial class Initial : DbMigration
{
public override void Up()
{
CreateTable(
"dbo.Measurements",
c => new
{
Id = c.Long(nullable: false, identity: true),
MTime = c.DateTime(nullable: false),
Value = c.Double(nullable: false),
TypeName = c.String(),
})
.PrimaryKey(t => t.Id);
}
public override void Down()
{
DropTable("dbo.Measurements");
}
}