C# 实体框架:如何在模型对象上组合 .Find 和 .Include? [英] C# Entity-Framework: How can I combine a .Find and .Include on a Model Object?
问题描述
我正在做 mvcmusicstore 练习教程.我在为相册管理器创建脚手架时注意到了一些东西(添加删除编辑).
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:
相册 = 项目
流派 = 类别
艺术家 = 品牌
以下是检索索引的方式(由 MVC 生成):
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.
我如何编写第二个来进行查找并填充里面的内容(最好在 1 行中)...理论上 - 类似于:
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);
推荐答案
您可以先使用 Include()
,然后从结果查询中检索单个对象:
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);
这篇关于C# 实体框架:如何在模型对象上组合 .Find 和 .Include?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!