Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
277 views
in Technique[技术] by (71.8m points)

asp.net mvc - C# Entity-Framework: How can I combine a .Find and .Include on a Model Object?

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);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...