实体框架4.1 InverseProperty属性

问题描述 投票:37回答:2

只是想了解更多有关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;}
}
c# entity-framework-4.1 data-annotations
2个回答
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属性仅在关系的一端是必需的,我们可以省略另一端的属性。)


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

© www.soinside.com 2019 - 2024. All rights reserved.