gpt4 book ai didi

c# - 如何在 DbSet.Find() 中包含相关表?

转载 作者:太空狗 更新时间:2023-10-30 00:30:17 24 4
gpt4 key购买 nike

如果我想在 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com