是否可以在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代码中首先使用具有继承的单表层次结构的复杂类型?
好的,我在EF 5 beta测试,但我认为这应该是一样的。这是一种变通方法,但你可能能够接受。当这是一个复杂类型时,鉴别符部分似乎不起作用,所以我在各自的构造函数中初始化了它。
我有这个,它工作:
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");
}
}