实体框架代码首先查找vs单一默认(Eager Loading) [英] Entity Framework Code First Find vs SingleOrDefault (Eager Loading)
问题描述
我正在使用Entity Framework 4.2(Code First)来访问我的数据库。我假设如果我使用 SingleOrDefault
查询实体,那么只有在实体尚未被跟踪的情况下才会查询数据库,但这似乎不是这样。另一方面,查找
方法似乎是这样做的。 Find
的问题是,似乎不允许我加载相关数据。
I'm using Entity Framework 4.2 (Code First) to access my database. I was under the assumption that if I queried an entity using SingleOrDefault
it would only query the database if the entity was not already being tracked, but this does not appear to be the case. The Find
method on the other hand, does appear to be doing this. The problem with Find
is that it doesn't appear to allow me to load related data.
是否有方式使用查找
方法,但也急切加载数据?例如,我想加载一本书及其所有评论:
Is there a way to use the Find
method but also eagerly load data ? As an example, I want to load a book and all of its reviews:
// Load book from the database
Book book = context.Books.Find(1);
context.Entry<Book>(book).Collection<Review>.Load(); // Book.Reviews is now populated
// Load book from the change tracker
// This will include all Reviews as well
Book book2 = context.Books.Find(1);
使用 SingleOrDefault
我可以加载评论我得到这本书使用包括:
With SingleOrDefault
I can load the Reviews when I get the book using Include:
// Load book + reviews from the database
Book book = Book.Include("Reviews").SingleOrDefault(b => b.Id == 1);
// Doing the same thing again requeries the database
Book book2 = Book.Include("Reviews").SingleOrDefault(b => b.Id == 1);
有没有办法获取行为找到
加载 SingleOrDefault
?
推荐答案
Find
方法是通过键搜索单个实体。 SingleOrDefault
方法用于执行查询。渴望加载只能是数据库中真正执行的查询的一部分,因此不能与 Find
一起使用。
The Find
method is for searching single entity by key. The SingleOrDefault
method is for executing query. Eager loading can be only part of the query which is really executed on the database so it cannot be used with Find
.
作为一种解决方法,您可以通过以下方法重写:
As a workaround you can rewrite it this way:
// This will check only on in-memory collection of loaded entities
Book book = context.Books.Local.SingleOrDefault(b => b.Id == 1);
if (book == null)
{
book = context.Books.Include(b => b.Review).SingleOrDefault(b => b.Id == 1);
}
这篇关于实体框架代码首先查找vs单一默认(Eager Loading)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!