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

相關問題