6

因此,我想使用Code First与Fluent将基类映射为一种派生类型,其中表架构是一个表类型安排。此外,派生类型与另一个也有复合外键的类型具有多对一的关系。 (关于这些表的键是不可改变和名称完全匹配,这。)EF 4.3代码优先:具有复合主键和外键的每种类型的表(TPT)

这里是我想要的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不支持具有在碱类型定义的属性,然后用它作为一个在一个外键的一部分 响应派生类型。不幸的是,这是一个很难从我们的代码库中删除的限制。鉴于我们没有看到很多要求,我们现在不打算在这个阶段解决这个问题,所以我们正在解决这个问题。

+0

我认为这些字段是现实生活中的属性? –

+1

我相信这是一个不支持的映射方案(至少我从来没有找到解决方案):http://stackoverflow.com/questions/10961690/inheritance-and-composite-foreign-keys-one-part-of-the-key- in-base-class- – Slauma

+0

我绝对认为目前不可能,但“不支持”?这是一个完全有效的配置,我从来没有在文档中发现任何可能表明这不应该起作用的东西,这似乎更像是一个错误。 – MDADev

回答

1

我认为这是你在找什么:

[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); 
    } 
} 

Code above results in:

+0

在我的情况'其他类型'不能是一个复杂的类型。它在不同的表格中,是一个实体本身,并且具有它自己的关系。 – MDADev

相关问题