gpt4 book ai didi

c# - Entity Framework 4.1 InverseProperty 属性

转载 作者:IT王子 更新时间:2023-10-29 04:00:39 27 4
gpt4 key购买 nike

只是想了解更多关于 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 Code 相同的关系:

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 属性仅在关系的一端是必需的,我们可以省略另一端的属性。)

关于c# - Entity Framework 4.1 InverseProperty 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5716528/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com