CodeFirst - EntityFrameWork 中的多层包含问题

25

这是有效的代码;

IQueryable<Product> productQuery = ctx.Set<Product>().Where(p => p.Id == id).(Include"Contexts.AdditionalProperties.Field");

但你知道,即使我们在 "Contexts.AdditionalProperties.Field" 的字符串语句中犯了错误,它也不会产生编译时错误。

我想编写下面的代码;

IQueryable<Product> productQuery = ctx.Set<Product>().Where(p => p.Id == id).Include(p => p.Contexts);

但是上述语句不能为定义AdditionalProperties和Field提供机会。

我们应该怎么办?

我想写多个include来构建查询。

谢谢。

1个回答

43

如果AdditionalProperties是指向另一个对象的单个引用:

using System.Data.Entity;
...
IQueryable<Product> productQuery = ctx.Set<Product>()
        .Include(p => p.Contexts.AdditionalProperties.Field)
        .Where(p => p.Id == id);
如果 AdditionalProperties 是一个集合,那么您可以使用 Select 方法:
IQueryable<Product> productQuery = ctx.Set<Product>()
        .Include(p => p.Contexts.AdditionalProperties.Select(a => a.Field))
        .Where(p => p.Id == id);

在你的类文件中不要忘记导入 System.Data.Entity 命名空间!


我必须告诉你,那不是一场公平的比赛...因为我几个月前在这里回答了这个问题。对不起! - Morteza Manavi
谢谢您的快速回答!我如何为AdditionalProperties添加另一个where条件,它是一个List<>类型的对象? - Nuri YILMAZ
3
你做不到。Include不能在导航属性上进行条件加载。为此,你需要消除Include并通过使用匿名类型的过滤投影来加载已过滤的导航属性。请查看这个帖子:https://dev59.com/YXA65IYBdhLWcg3wogEb#3718457 - Morteza Manavi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接