gpt4 book ai didi

c# - 如何构建一个允许我通过参数为 EF 传递多个包含的函数?

转载 作者:太空宇宙 更新时间:2023-11-03 13:07:12 25 4
gpt4 key购买 nike

我正在编写一个 EF 支持的存储库,该存储库具有与每个实体类型相关联的包的概念,这些实体类型对其常用子项执行 .Include。例如,我有一个看起来像这样的函数

private static IQueryable<Foo> GetFooPackage(Entities context)
{
return context.Foo
.Include(target => target.Bar)
.Include(target => target.FooBar)
}

当我运行我的“get”方法时,返回数据的分组是一致的。但是,我希望能够根据具体情况对此进行扩展。我希望能够做类似的事情

public static Foo GetFoo(int fooId, params Expression<Func<Foo, T>>[] extraIncludes)
{
using (Entities context = GetContext(null))
{
IQueryable<Foo> package = GetFooPackage(context);

extraIncludes.ToList().ForEach(expression => package.Include(expression));

return package.FirstOrDefault(target => target.FooId == fooId);
}
}

让我感到困惑的是 T 部分。我知道该示例没有正确引用 T 泛型。它只是示例的占位符。我不确定如何塑造它以便我可以做我想做的事。最终,努力使 EF 生成的 SQL 尽可能小和整洁。你有什么建议?它在断开连接的服务中使用,所以我不能依靠延迟加载来简单地获取更多丢失的数据。抓取数据后,我需要一次性获取它,而进行第二次抓取确实不切实际。

谢谢!

最佳答案

public IQueryable<T> GetAllIncluding(params Expression<Func<T, object>>[] includes)
{
var query = DbSet.AsNoTracking();

query = includes.Aggregate(query, (current, includeProperty) => current.Include(includeProperty));

return query;
}

MyGenericRepository<A>().GetAllIncluding(x=> x.B, x=> x.C).FirstOrDefault()

在这里找到答案:How to include 2 navigational properties in EF?

关于c# - 如何构建一个允许我通过参数为 EF 传递多个包含的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30352895/

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