1

使用實體框架:代碼首先,我嘗試使用基類的導航屬性定義集合導航屬性。使用繼承的集合導航屬性(每種類型的表格)

對象結構:

public class Content 
{ 
    public int ID { get; set; } 
    public ModerationStatuses ModerationStatus { get; set; } 
    public ContentItemTypes ContentType { get; set; } 
    public virtual User Author { get; set; } 
} 

public class Image : Content 
{ 
    public Image() 
     : base() 
    { 
     ContentType = ContentItemTypes.Image; 
    } 
    public string FileName { get; set; } 
    public string Location { get; set; } 
    public int DisplayOrder { get; set; } 
    public long FileSize { get; set; } 
} 

public class User 
{ 
    public int UserID { get; set; } 
    public string Username { get; set; } 

    public virtual ICollection<Image> Images { get; set; } 
} 

語境OnModelCreating:

modelBuilder.Entity<Content>() 
    .Map(i => i.ToTable("Content")); 

modelBuilder.Entity<Image>() 
    .Map(i => i.ToTable("Images")); 

當生成數據庫,它創建了一個User_UserID外鍵約束到的圖像表,而不是在內容表使用Author_UserID。

如何才能將它識別爲Content ..Author_UserID字段作爲ICollection<Image>導航屬性的外鍵?

回答

1

這是不可能的。您需要將Author財產從Content轉移到Image類別使User類型ICollection<Content> Contents的收集。導航屬性必須始終爲,在逆導航屬性引用的實體類中聲明爲。它不能從基礎實體繼承。

0

其實它是可能的......你只需要添加一個導航屬性到你的內容類,然後你有一個引用映射到。

這裏是全面的walkthrough