【发布时间】:2011-05-26 16:34:31
【问题描述】:
我一直在查看Applying filters when explicitly loading related entities,但无法使其适用于多对多关系。
我创建了一个简单的模型:
简要说明:
一个Student 可以包含多个Courses,一个Course 可以包含多个Students。
一个Student 可以生成多个Presentation,但一个Presentation 只能生成一个Student。
所以我们拥有的是Students 和Courses 之间的多对多关系,以及Student 和Presentations 之间的一对多关系。
我还添加了一个Student、一个Course 和一个Presentation。
这是我正在运行的代码:
class Program
{
static void Main()
{
using (var context = new SportsModelContainer())
{
context.Configuration.LazyLoadingEnabled = false;
context.Configuration.ProxyCreationEnabled = false;
Student student = context.Students.Find(1);
context.
Entry(student).
Collection(s => s.Presentations).
Query().
Where(p => p.Id == 1).
Load();
context.
Entry(student).
Collection(s => s.Courses).
Query().
Where(c => c.Id == 1).
Load();
// Trying to run Load without calling Query() first
context.Entry(student).Collection(s => s.Courses).Load();
}
}
}
加载演示文稿后,我看到 Presentations 的计数从 0 变为 1: 。 但是,在对 Courses 执行相同操作后,没有任何变化:
所以我尝试在不调用 Query 的情况下加载课程,它按预期工作:
(我删除了Where 子句以进一步强调这一点 - 最后两次加载尝试仅因“Query()”调用不同)
现在,我看到的唯一区别是一种关系是一对多的,而另一种是多对多的。这是一个 EF 错误,还是我遗漏了什么?
顺便说一句,我检查了最后两次 Course-loading 尝试的 SQL 调用,它们 100% 相同,所以似乎是 EF 未能填充集合。
【问题讨论】:
标签: entity-framework entity-framework-4.1