所以我尝试使用代码优先和 Fluent 将基类映射到一个派生类型,其中表架构是按类型排列的表。此外,派生类型与另一个也具有复合外键的类型具有多对一关系。 (这些表上的键是不可更改的,名称完全匹配。)
这是我试图在 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});
}
据我所知,我的映射设置正确(例如,我遵循了许多具有这种确切情况但具有单个列标识符的教程和示例)
当我尝试查询这些实体时,我得到的异常是:
外键组件“TenantId”不是类型“DerivedType”的声明属性。
当我尝试使用 new
关键字在类型上显式声明这些属性时,我得到一个异常,指出存在重复的属性。
回答 来自 EF 团队的回应
This is part of a more fundamental limitation where EF doesn't support having a property defined in a base type and then using it as a foreign key in a derived type. Unfortunately this is a limitation that would be very hard to remove from our code base. Given that we haven't seen a lot of requests for it, it's not something we are planning to address at this stage so we are closing this issue.
最佳答案
我想这就是您要找的:
[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);
}
}
关于c# - EF 4.3 代码优先 : Table per Type (TPT) with Composite Primary Key and Foreign Key,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13179634/