Can someone explane the following code for me?
public class StoreEditorViewModel
{
public List<Ticket> TotalView { get; set; }
public StoreEditorViewModel()
{
using (MvcTicketsEntities storeDB = new MvcTicketsEntities())
{
var temp = storeDB.Tickets.Include(x => x.Genres).Include(x => x.Artists).ToList();
TotalView = temp.ToList();
}
}
}
I don’t understand the Inculde(x => x.genres) *genres is another table in my database. ( i use entity Framework)
The Include is telling EF to fetch the Genres records as part of this sql request, rather than making you call twice (once for Tickets and again for the Tickets Genres).
To quote Jon Galloway in the MVC Music Store example (your code looks very similar)
“We’ll take advantage of an Entity Framework feature that allows us to indicate other related entities we want loaded as well when the Genre object is retrieved. This feature is called Query Result Shaping, and enables us to reduce the number of times we need to access the database to retrieve all of the information we need. We want to pre-fetch the Albums for Genre we retrieve, so we’ll update our query to include from Genres.Include(“Albums”) to indicate that we want related albums as well. This is more efficient, since it will retrieve both our Genre and Album data in a single database request.”