【发布时间】:2012-05-12 19:35:30
【问题描述】:
我喜欢 EF Code First,但有时似乎只在 SQL 中定义表会更容易。
在这种情况下,我有两个模型,如下所示:
public class Book
{
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<BookRecommendation> BookRecommendations { get; set; }
// additional properties about the item
}
public class BookRecommendation
{
public int Id { get; set; }
// public int BookId { get; set; } // from attempts to use data annotations
public virtual Book Book { get; set; }
// public int BookRecommendedId { get; set; } // from attempts to use data annotations
public virtual Book BookRecommended { get; set; }
// additional properties about the relationship between the two items
}
不幸的是,我无法让它与数据注释或流式 API 一起正常工作。
有Multiple foreign keys pointing to same table in Entity Framework 4.1 code first、Entity Framework 4.1 InverseProperty Attribute and ForeignKey之类的问题,但这些问题往往涉及两端的集合。
我的模型可能是错误的,因为很早就开始感到沮丧,我考虑如何在 SQL 中做到这一点:
Book
Id
Name
// other properties
Recommendation
Id
BookId
RecommendedBookId
// other properties
Book.Id : Recommendation.BookId 和 Book.Id : Recommendation.RecommendedBookId 之间会有外键。
我需要通过数据注释或流畅的 API 做什么才能使其正常工作,或者我应该如何修改我的模型?
【问题讨论】:
-
老实说,鉴于这个问题已经超过 4 年了,我不能说 100% 是否可能与该问题重复。但是基于该问题的两个最高评分的答案,以及 13 年 3 月对这个问题的最后一个答案,我似乎没有得到例外,但可能与我的数据库优先假设不匹配的表,我会倾向于这些与众不同。
-
“可能重复”是一种清理方法 - 关闭类似问题并保留最佳答案。见meta.stackexchange.com/questions/147643/…
标签: ef-code-first