SingleOrDefault vs. Entity Framework Code First Find (Eager Loading)

c# ef-code-first entity-framework

Question

To access my database, I'm using Entity Framework 4.2 (Code First). I believed that if I used a certain method to query an object,SingleOrDefault If the object was not already being tracked, it would just query the database; however, this does not seem to be the case. TheFind On the other hand, technique does seem to be doing this. The issue withFind the fact that it doesn't seem to let me load relevant data.

Is it possible to utilize theFind but eagerly load data as well? I wish to load a book and all of its reviews as an illustration:

// 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 When I get the book, I may load the reviews 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);

Is it possible to influence the behavior ofFind while eagerly loadingSingleOrDefault ?

1
14
2/12/2015 11:18:24 AM

Accepted Answer

The Find technique is for key-based searches on single entities. TheSingleOrDefault method is used to carry out a query. Eager loading may only run a portion of the query on the database, hence it cannot be utilized withFind .

You may modify it in this fashion as a workaround:

// 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);
}
13
4/11/2012 7:44:27 PM

Popular Answer

Whenever slow loading is enabled Find what will work for you. Do this:

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

Verify the "n" variable's value. When you first access a collection, EF must load it.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow