【问题标题】:Multi-Level Includes in CodeFirst - EntityFrameWorkCode First 中的多级包含 - 实体框架
【发布时间】:2011-06-12 15:53:18
【问题描述】:

这是工作代码;

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 的机会。

我们应该怎么做?

我想为构建查询编写多个包含。

谢谢。

【问题讨论】:

    标签: entity-framework entity-framework-ctp5


    【解决方案1】:

    如果 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 命名空间!

    【讨论】:

    • 我必须告诉你,这是一场公平的比赛......因为几个月前我在这里回答了这个问题。对不起老兄!
    • 感谢您的快速答复!如何为 AdditionalProperties 添加另一个 where contion,它是 List 类型的对象?
    • 你不能。 Include 不允许在导航属性上进行条件加载。为此,您需要通过具有匿名类型的 Filtered Projection 消除 Include 并加载过滤后的导航属性。看看这个线程:stackoverflow.com/questions/3718400/conditional-eager-loading/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多