entity framework4.1 InverseProperty属性

只是想知道更多关于RelatedTo属性,我发现它已被EF 4.1 RC中的ForeignKeyInverseProperty属性所取代。

有没有人知道这个属性变得有用的场景的任何有用的资源?

我应该在导航属性上使用这个属性吗? 例:

 public class Book { public int ID {get; set;} public string Title {get; set;} [ForeignKey("FK_AuthorID")] public Author Author {get; set;} } public class Author { public int ID {get; set;} public string Name {get; set;} // Should I use InverseProperty on the following property? public virtual ICollection<Book> Books {get; set;} } 

我为InversePropertyAttribute添加一个示例。 它不但可以用于自引用实体的关系(如Ladislav的答案中所链接的例子),也可以用于不同实体之间关系的“正常”情况:

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

这将描述与此Fluent代码相同的关系:

 modelBuilder.Entity<Book>() .HasOptional(b => b.Author) .WithMany(a => a.Books); 

… 要么 …

 modelBuilder.Entity<Author>() .HasMany(a => a.Books) .WithOptional(b => b.Author); 

现在,在上面的示例中添加InverseProperty属性是多余的:映射约定会创build相同的单一关系

但是考虑一下这个例子(一个书库只包含两位作者的书):

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

映射约定不会检测到这些关系的哪一端属于一起,而是实际创build四个关系 (在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属性只在关系的一端是必需的,我们可以省略另一端的属性。)

ForeignKey属性与导航属性配对FK属性。 它可以放置在FK属性或导航属性上。 它相当于HasForeignKeystream畅映射。

 public class MyEntity { public int Id { get; set; } [ForeignKey("Navigation")] public virtual int NavigationFK { get; set; } public virtual OtherEntity Navigation { get; set; } } 

InverseProperty用于定义两端的自引用关系和配对导航属性。 检查这个问题的示例 。