C# Entity-Framework: How to combine a .Find and .Include on a Model Object

asp.net-mvccentity-framework

I'm doing the mvcmusicstore practice tutorial. I noticed something when creating the scaffold for the album manager (add delete edit).

I want to write code elegantly, so i'm looking for the clean way to write this.

FYI i'm making the store more generic:

Albums = Items

Genres = Categories

Artist = Brand

Here is how the index is retrieved (generated by MVC):

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

Here is how the item for delete is retrieved:

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

The first one brings back all the items and populates the category and brand models inside the item model. The second one, doesn't populate the category and brand.

How can i write the second one to do the find AND populate whats inside (preferably in 1 line)… theoretically – something like:

Item item = db.Items.Find(id).Include(i => i.Category).Include(i => i.Brand);

Best Answer

You can use Include() first, then retrieve a single object from the resulting query:

Item item = db.Items
              .Include(i => i.Category)
              .Include(i => i.Brand)
              .FirstOrDefault(x => x.ItemId == id);