C#实体框架:如何可以结合.Find和.INCLUDE一个模型对象? [英] C# Entity-Framework: How can I combine a .Find and .Include on a Model Object?

查看:87
本文介绍了C#实体框架:如何可以结合.Find和.INCLUDE一个模型对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我做的mvcmusicstore实践教程。创建相册管理器支架(添加删除编辑)时,我注意到的东西。

我要优雅地写code,所以我在寻找清洁的方式来写这个。

FYI我正在做实体店更通用的:

专辑=项目

流派=分类

艺术家=品牌

下面是该指数如何检索(由MVC生成):

  VAR项目= db.Items.Include(I => i.Category).INCLUDE(I => i.Brand);

下面是如何对删除的项进行检索:

 项项= db.Items.Find(ID);

第一个带回的所有项目,并填充项目模型内部的品类和品牌车型。第二个,不填充品类和品牌。

我怎么能写第二个做查找和填充里面什么($ P在1号线pferably $)...理论上 - 是这样的:

 项项= db.Items.Find(ID).INCLUDE(I => i.Category).INCLUDE(I => i.Brand);


解决方案

您需要使用包括(),然后再检索结果查询单个对象:

 逐项= db.Items
              .INCLUDE(I => i.Category)
              .INCLUDE(I => i.Brand)
              .SingleOrDefault(X => x.ItemId == ID);

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

解决方案

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

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

这篇关于C#实体框架:如何可以结合.Find和.INCLUDE一个模型对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆