0
我有一個MVC項目使用EF6.1,我需要添加另一個外鍵到模型。我對這個領域很陌生,在添加遷移時遇到錯誤。EntityFramework兩個外鍵代碼優先遷移問題
我已經到位3個表(標籤,內容頁)目前FK內容&之間的標籤定義 創建Tags_Content表對我的系統。
pubic class Content {
int Id { get; set; }
string Title { get; set; }
public virtual ICollection<Tag> Tags { get; set; }
public static new void Configure<TSelf>(EntityTypeConfiguration<TSelf> configuration)
where TSelf : Content
{
configuration.HasMany(o => o.Tags)
.WithMany(t => (ICollection<TSelf>)t.Content)
.Map(c => c.ToTable("Tags_Content"));
}
}
class Page : Content {
// extends general content
}
class Tag {
int Id { get; set; }
string Name { get; set; }
// add a column to Tags which will be the FK to Content or Pages
// the purpose is to implement an option of assigning additional page (or content) to a tag (the PageId is null or any page)
public int? PageId { get; set; }
public virtual Page Page { get; set; }
public static new void Configure<TSelf>(EntityTypeConfiguration<TSelf> configuration)
where TSelf : Tag
{
configuration.HasMany(a => a.Content)
.WithMany(a => (ICollection<TSelf>)a.Tags)
.Map(c => c.ToTable("Tags_Content"));
}
}
我沒有寫出定義FK的正確配置。任何人都可以幫助我嗎?謝謝。
您是否面臨任何異常?哪個例外?您是否正在尋找一種方法來指定表格'Tags_Content'中的列名稱? –
嗨Jenish,我不會遇到任何異常。上面的代碼很好。我需要的是添加將創建FK的配置語句,其中PageId引用Content/Page並且可以爲NULL。我已經嘗試了幾次,但總是以錯誤的方式導致EF未能創建添加遷移模型。 – Tomas
我在你的代碼中發現的一個錯誤是你在'Content'類中定義了兩次多對多的關係,而在'Tag'中定義了另一個關係。這是錯誤的。您需要刪除任何一條語句。 –