[英]EF 4.3 Code First: Table per Type (TPT) with Composite Primary Key and Foreign Key
所以我正在尝试使用Code First和Fluent来映射具有一种派生类型的基类,其中表模式是Table-per-Type排列。 此外,派生类型与具有复合外键的另一种类型具有多对一关系。 (这些表上的键是不可更改的,名称完全匹配。)
以下是我在CSharp中尝试实现的示例:
public class BaseType
{
public int Id;
public int TenantId;
public int Name;
}
public class DerivedType : BaseType
{
public int Active;
public int OtherTypeId;
public OtherType NavigationProperty;
}
以下是配置类中的配置:
public BaseTypeConfiguration()
{
ToTable("BaseTypes", "dbo");
HasKey(f => new { f.Id, f.TenantId});
Property(f => f.Id)
.HasColumnName("BaseTypeId")
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
}
public DerivedTypeConfiguration()
{
ToTable("DerivedTypes", "dbo");
//OtherType has many DerivedTypes
HasRequired(dt=> dt.OtherTypeNavigation)
.WithMany(ot=> ot.DerivedTypes)
.HasForeignKey(dt=> new { dt.OtherTypeId, dt.TenantId});
}
从我可以告诉我的映射是正确设置的(例如,我遵循了许多具有这种确切情况但具有单个列标识符的教程和示例)
当我尝试查询这些实体时,我得到的异常是: The foreign key component 'TenantId' is not a declared property on type 'DerivedType'.
当我尝试使用new
关键字在类型上显式声明这些属性时,我得到一个异常,说明存在重复属性。
回答 EF团队的回复
这是更基本的限制的一部分,其中EF不支持在基类型中定义属性,然后将其用作派生类型中的外键。 不幸的是,这是一个很难从我们的代码库中删除的限制。 鉴于我们没有看到很多请求,这不是我们计划在这个阶段解决的问题所以我们正在关闭这个问题。
我认为这就是你要找的东西:
[Table("BaseType")]
public class BaseType
{
[Key, DatabaseGenerated(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.Identity)]
public int Id {get;set;}
[Key]
public int TenantId { get; set; }
public int Name { get; set; }
}
[Table("Derived1")]
public class DerivedType : BaseType
{
public int Active { get; set; }
public int OtherTypeId { get; set; }
public virtual OtherType NavigationProperty {get;set;}
}
[ComplexType]
public class OtherType
{
public string MyProperty { get; set; }
}
public class EFCodeFirstContext : DbContext
{
public DbSet<BaseType> BaseTypes { get; set; }
public DbSet<DerivedType> DerivedTypes { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<BaseType>().HasKey(p => new { p.Id, p.TenantId });
base.OnModelCreating(modelBuilder);
}
}
根据他们的支持,目前尚未得到支持。 我在这里创建了一个类似堆栈问题的案例,并且作者使用案例结果进行了更新。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.