实体框架4.1 InverseProperty属性

| 我只是想了解更多关于
RelatedTo
属性的信息,我发现它在EF 4.1 RC中已被
ForeignKey
InverseProperty
属性所取代。 有人知道有关此属性有用的方案的任何有用资源吗? 我应该在导航属性上使用此属性吗?例:
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;}
}
已邀请:
我为“ 4”添加一个示例。它不仅可用于自引用实体中的关系(如在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);
现在,在上面的示例中添加2属性是多余的:映射约定总会创建相同的单一关系。 但是,请考虑以下示例(一个仅包含由两位作者共同撰写的书籍的图书库):
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;}
}
在这里,我们只会得到两个关系。 (注意:only2ѭ属性仅在关系的一端是必需的,我们可以在另一端省略该属性。)
“ 1”属性将FK属性与导航属性配对。可以将其放在FK属性或导航属性上。它等效于“ 14”流利绘图。
public class MyEntity
{
    public int Id { get; set; }

    [ForeignKey(\"Navigation\")]
    public virtual int NavigationFK { get; set; }

    public virtual OtherEntity Navigation { get; set; }
}
InverseProperty
用于定义自引用关系和两端的配对导航属性。检查此问题以获取样本。

要回复问题请先登录注册