MDA*_*Dev 6 c# table-per-type composite-primary-key ef-code-first entity-framework-4.3
所以我正在尝试使用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;
}
Run Code Online (Sandbox Code Playgroud)
以下是配置类中的配置:
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});
}
Run Code Online (Sandbox Code Playgroud)
从我可以告诉我的映射是正确设置的(例如,我遵循了许多具有这种确切情况但具有单个列标识符的教程和示例)
当我尝试查询这些实体时,我得到的异常是:
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);
}
}
Run Code Online (Sandbox Code Playgroud)

| 归档时间: |
|
| 查看次数: |
1611 次 |
| 最近记录: |