Entity Framework/C#: multiple includes from string array?(实体框架/C#:来自字符串数组的多个包含?)
问题描述
如果想在某些实体框架选择上使用 Include()
方法(以避免对象已处置"异常).但是 Include 只接受一个字符串作为参数,这意味着只包含一个.要执行多个包含,您必须链包含 .Include("something").Include("something").Include("something")
If want to use the Include()
method on some Entity Framework selection (in order to avoid the 'Object as been disposed' exception).
But Include only accepts one string as parameter which means one include only.
To do multiple include, you must chain includes .Include("something").Include("something").Include("something")
但我希望我的包含来自字符串数组.
But I would like my includes to come from a string array.
所以我想写的是 .Include(array[0]).Include(array[1]).Include(array[2])...Include(array[n])
(其中'n' = array.Length - 1)
(Where 'n' = array.Length - 1)
当然我事先不知道字符串数组中会是什么.
Of course I don't know in advance what will be in the string array.
但到目前为止我找不到正确的语法.谢谢你的帮助
But I can't find the correct syntax so far. Thank you for your help
鉴于我到目前为止的建议,我想说请准确说明类型并避免空值问题并对其进行测试.到目前为止,似乎没有任何解决方案有效,我迷失在我能用这种或那种类型做什么和不能做什么.
Given the suggetions I've had so far, I'd say please be precise about type and avoiding null value problems and test it. So far no solution seems to work and I get lost in what I can and can't do with this or that type.
推荐答案
你可以使用 params string[]
让你的代码更清晰:
You can use params string[]
which will make your code even clearer:
public static IQueryable<T> Include<T>(this IDbSet<T> dbSet, params string[] includes) where T : class
{
foreach (var include in includes)
dbSet.Include(include);
return dbSet;
}
那么你可以同时使用它:
Then you can use it both ways:
.Include("NavProp1", "NavProp2", "NavProp3");
还有:
.Include(new[] { "NavProp1", "NavProp2", "NavProp3" });
这篇关于实体框架/C#:来自字符串数组的多个包含?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:实体框架/C#:来自字符串数组的多个包含?


- C# 中多线程网络服务器的模式 2022-01-01
- 输入按键事件处理程序 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- 如何用自己压缩一个 IEnumerable 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- MoreLinq maxBy vs LINQ max + where 2022-01-01