Ral*_*h N 137 c# asp.net-mvc entity-framework
我正在做mvcmusicstore练习教程.我在为专辑管理器创建脚手架时注意到了一些事情(添加删除编辑).
我想优雅地编写代码,所以我正在寻找干净的方式来编写它.
仅供参考我正在使商店更通用:
专辑=项目
类型=类别
艺术家=品牌
以下是检索索引的方式(由MVC生成):
var items = db.Items.Include(i => i.Category).Include(i => i.Brand);
Run Code Online (Sandbox Code Playgroud)
以下是检索删除项的方法:
Item item = db.Items.Find(id);
Run Code Online (Sandbox Code Playgroud)
第一个带回所有项目并填充项目模型中的类别和品牌模型.第二个,没有填充类别和品牌.
我怎么能写第二个来做查找并填充里面的内容(最好是一行)...理论上 - 类似于:
Item item = db.Items.Find(id).Include(i => i.Category).Include(i => i.Brand);
Run Code Online (Sandbox Code Playgroud)
Den*_*aub 150
您需要先使用Include()
,然后从生成的查询中检索单个对象:
Item item = db.Items
.Include(i => i.Category)
.Include(i => i.Brand)
.SingleOrDefault(x => x.ItemId == id);
Run Code Online (Sandbox Code Playgroud)
Lea*_*ner 68
丹尼斯的回答是使用Include
和SingleOrDefault
.后者绕过数据库.
另一种方法是Find
结合使用Load
,明确加载相关实体......
在MSDN示例下面:
using (var context = new BloggingContext())
{
var post = context.Posts.Find(2);
// Load the blog related to a given post
context.Entry(post).Reference(p => p.Blog).Load();
// Load the blog related to a given post using a string
context.Entry(post).Reference("Blog").Load();
var blog = context.Blogs.Find(1);
// Load the posts related to a given blog
context.Entry(blog).Collection(p => p.Posts).Load();
// Load the posts related to a given blog
// using a string to specify the relationship
context.Entry(blog).Collection("Posts").Load();
}
Run Code Online (Sandbox Code Playgroud)
当然Find
,如果该实体已经被上下文加载,则立即返回而不向商店发出请求.
归档时间: |
|
查看次数: |
70690 次 |
最近记录: |