我爲InversePropertyAttribute
添加了一個示例。它不僅可以用於自參考實體的關係(如在拉吉斯拉夫的答案鏈接的例子),但也可在不同實體之間的關係的「正常」的情況下:
public class Book
{
public int ID {get; set;}
public string Title {get; set;}
[InverseProperty("Books")]
public Author Author {get; set;}
}
public class Author
{
public int ID {get; set;}
public string Name {get; set;}
[InverseProperty("Author")]
public virtual ICollection<Book> Books {get; set;}
}
這會形容爲這個同樣的關係流利代碼:
modelBuilder.Entity<Book>()
.HasOptional(b => b.Author)
.WithMany(a => a.Books);
......或者......
modelBuilder.Entity<Author>()
.HasMany(a => a.Books)
.WithOptional(b => b.Author);
現在,將在上面的例子中InverseProperty
屬性是redundan t:映射規則無論如何都會創建相同的單一關係。
但考慮這個例子(圖書閱覽室,僅包含由兩位作者一起寫的書的):
public class Book
{
public int ID {get; set;}
public string Title {get; set;}
public Author FirstAuthor {get; set;}
public Author SecondAuthor {get; set;}
}
public class Author
{
public int ID {get; set;}
public string Name {get; set;}
public virtual ICollection<Book> BooksAsFirstAuthor {get; set;}
public virtual ICollection<Book> BooksAsSecondAuthor {get; set;}
}
約定就無法檢測到映射這些關係,從而結束屬於一起,實際上創造四個關係(Books表中有四個外鍵)。在這種情況下使用InverseProperty
將有助於確定我們要正確的關係,我們的模型:
public class Book
{
public int ID {get; set;}
public string Title {get; set;}
[InverseProperty("BooksAsFirstAuthor")]
public Author FirstAuthor {get; set;}
[InverseProperty("BooksAsSecondAuthor")]
public Author SecondAuthor {get; set;}
}
public class Author
{
public int ID {get; set;}
public string Name {get; set;}
[InverseProperty("FirstAuthor")]
public virtual ICollection<Book> BooksAsFirstAuthor {get; set;}
[InverseProperty("SecondAuthor")]
public virtual ICollection<Book> BooksAsSecondAuthor {get; set;}
}
在這裏,我們只會得到兩個關係。 (注意:InverseProperty
屬性只在關係的一端有必要,我們可以省略另一端的屬性。)
+1好。我希望你會來解釋一點點,以獲得一些學分:) – 2011-04-19 13:45:11
哈哈!但不知何故,這個屬性在約定和Fluent映射之間的無人區域中:對於簡單的關係來說,這不是必要的,而且對於複雜的關係,每個人都會使用Fluent代碼。可能是爲什麼它是如此不尋常的原因,我可以想到的唯一解釋是爲什麼即使你*不知道它:) – Slauma 2011-04-19 14:48:46
感謝您的洞察力的答案。 – Kamyar 2011-04-20 05:56:06