简体   繁体   English

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

[英]Entity Framework Code First Find vs SingleOrDefault (Eager Loading)

I'm using Entity Framework 4.2 (Code First) to access my database. 我正在使用Entity Framework 4.2(代码优先)来访问我的数据库。 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. 我假设如果我使用SingleOrDefault查询实体,它只会在实体尚未被跟踪的情况下查询数据库,但事实并非如此。 The Find method on the other hand, does appear to be doing this. 另一方面, Find方法似乎确实这样做了。 The problem with Find is that it doesn't appear to allow me to load related data. Find的问题在于它似乎不允许我加载相关数据。

Is there a way to use the Find method but also eagerly load data ? 有没有办法使用Find方法,但也急切地加载数据? 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);

With SingleOrDefault I can load the Reviews when I get the book using Include: 使用SingleOrDefault我可以在使用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);

Is there a way to get the behavior of Find with the eager loading of SingleOrDefault ? 有没有办法通过急切加载SingleOrDefault来获取Find的行为?

The Find method is for searching single entity by key. Find方法用于按键搜索单个实体。 The SingleOrDefault method is for executing query. SingleOrDefault方法用于执行查询。 Eager loading can be only part of the query which is really executed on the database so it cannot be used with Find . 渴望加载只能是在数据库上真正执行的查询的一部分,因此它不能与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);
}

If lazy-loading is enable Find will work for you. 如果启用延迟加载查找将适合您。 Try this: 尝试这个:

Book book = context.Books.Find(1);
int n = book.Reviews.Count;

Check the value for the "n" variable. 检查“n”变量的值。 EF must load the collection when you access it first time. EF必须在您第一次访问时加载该集合。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM