实体框架代码首先查找vs SingleOrDefault(Eager Loading)

Dis*_*ile 14 c# entity-framework ef-code-first

我正在使用Entity Framework 4.2(代码优先)来访问我的数据库.我假设如果我查询使用SingleOrDefault它的实体只会查询数据库是否实体尚未被跟踪,但事实并非如此.Find另一方面,该方法似乎确实这样做了.问题Find是它似乎不允许我加载相关数据.

有没有办法使用该Find方法,但也急切加载数据?例如,我想加载一本书及其所有评论:

// 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);
Run Code Online (Sandbox Code Playgroud)

随着SingleOrDefault我可以加载评论时,我得到使用包括书:

// 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);
Run Code Online (Sandbox Code Playgroud)

有没有办法Find通过急切加载来获得行为SingleOrDefault

Lad*_*nka 12

Find方法用于按键搜索单个实体.该SingleOrDefault方法用于执行查询.急切加载只能是在数据库上真正执行的查询的一部分,因此无法使用Find.

作为一种解决方法,您可以这样重写它:

// 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);
}
Run Code Online (Sandbox Code Playgroud)

  • 不知道这个当地财产的存在。谢谢! (2认同)