实体框架4.1 InverseProperty属性

时间:2011-04-19 12:44:04

标签: c# entity-framework-4.1 data-annotations

只是想了解有关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;}
}

2 个答案:

答案 0 :(得分:80)

我为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属性是多余的:映射约定无论如何都会创建相同的单一关系

但请考虑这个例子(图书馆只包含两位作者共同撰写的书籍):

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 :(得分:28)

ForeignKey属性将FK属性与导航属性配对。它可以放在FK属性或导航属性上。它相当于HasForeignKey流畅的映射。

public class MyEntity
{
    public int Id { get; set; }

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

    public virtual OtherEntity Navigation { get; set; }
}

InverseProperty用于定义两端的自引用关系和配对导航属性。检查this question for sample