作者热门文章
- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
如果我想在 EF7 查询中包含相关对象,这非常简单:
var myThing = db.MyThings
.Include(t => t.RelatedThing)
.Where(t => t.SomeCondition == true)
.ToList();
另外,DbSet<T>
上有一个很好的方法这使得通过其键加载单个对象变得容易:
var myThing = db.MyThings.Find(thingId);
但现在我想加载myThing
通过它的 Id,连同它的 RelatedThing
.不幸的是(也是可以理解的).Find()
是 DbSet<T>
的一种方法, 不是 IQueryable<T>
.显然我可以这样做:
var myThing = db.MyThings
.Include(t => t.RelatedThing)
.SingleOrDefault(t => t.MyThingId == thingId);
但我特别想使用 .Find()
方法,因为它很好而且通用,我正在编写一个方法,它通常加载记录以及 Expression<Func<T, object>>
指定的“包含”关系.
有什么建议如何做到这一点?
最佳答案
将 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();
}
这里是 MSDN link
关于c# - 如何在 DbSet.Find() 中包含相关表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39434878/
我是一名优秀的程序员,十分优秀!