实体框架/C#:来自字符串数组的多个包含? [英] Entity Framework/C#: multiple includes from string array?

查看:35
本文介绍了实体框架/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#:来自字符串数组的多个包含?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆