How can I mix a.Find and.Include on a Model Object in C# Entity Framework?

asp.net-mvc c# entity-framework

Question

I'm following the practice instruction from mvcmusicstore. While building the scaffold for the album manager, I came across this (add delete edit).

I'm searching for the cleanest method to do this since I want to create nice code.

FYI, I'm broadening the store's appeal:

Items = Albums

Categories = Genres

Brand = Artist

The index is fetched in the following manner (created by MVC):

var items = db.Items.Include(i => i.Category).Include(i => i.Brand);

Here is how to obtain the item to delete:

Item item = db.Items.Find(id);

The first one updates the category and brand models within the item model with all the products. The second one leaves out the brand and category.

How can I construct the second one to do the search AND fill the contents (ideally in a single line)? Theoretically, it may look like this:

Item item = db.Items.Find(id).Include(i => i.Category).Include(i => i.Brand);
1
142
1/22/2013 1:38:56 PM

Accepted Answer

You must useInclude() first, from the returned query, take one item out:

Item item = db.Items
              .Include(i => i.Category)
              .Include(i => i.Brand)
              .SingleOrDefault(x => x.ItemId == id);
155
9/20/2012 10:43:24 AM

Popular Answer

Dennis' response employsInclude and SingleOrDefault . The latter visits the database repeatedly.

A alternative option is to utilizeFind when combined withLoad in order to explicitly load associated items...

From zzz-25 to zzz:

using (var context = new BloggingContext()) 
{ 
  var post = context.Posts.Find(2); 

  // Load the blog related to a given post 
  context.Entry(post).Reference(p => p.Blog).Load(); 

  // Load the blog related to a given post using a string  
  context.Entry(post).Reference("Blog").Load(); 

  var blog = context.Blogs.Find(1); 

  // Load the posts related to a given blog 
  context.Entry(blog).Collection(p => p.Posts).Load(); 

  // Load the posts related to a given blog  
  // using a string to specify the relationship 
  context.Entry(blog).Collection("Posts").Load(); 
}

No doubt,Find If the object is already loaded by the context, it returns without sending a request to the store.



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