实体框架包含3个表的位置

Cod*_*313 4 .net entity-framework

我试图从一个基表中包含两个表,并在第二个表上提供"where"语句,但是我遇到了一个非常令人困惑的错误(下面).关于问题/解决方案的任何想法?

ObjectQuery<STATE> productQuery = 
    LeadsContext.STATE.Include("REGION")
      .Where("it.REGION.BRAND.BRAND_ID = @brand", new ObjectParameter("brand", brand))
      .OrderBy("it.STATE_ABBV");
Run Code Online (Sandbox Code Playgroud)

基本表格布局:STATE ------ REGION ------ BRAND

BRAND_ID在BRAND中

'BRAND'不是'Transient.collection [Citizens.Leads.Data.REGION(Nullable = True,DefaultValue =)]'的成员.要从集合中提取属性,必须使用子查询迭代集合.,靠近多部分标识符,第8行,第1列.

Ale*_*mes 6

听起来好像State.REGION实际上是一个Region实体的集合.

在这种情况下,您不能直接访问BRAND导航,因为您的语句尝试访问Collection的BRAND属性,而不是集合中元素的BRAND属性.

如果您使用LINQ to Entities而不是查询构建器方法编写此查询,则可以这样执行:

var productQuery = from s in LeadsContext.State
                   from r in s.REGION
                   where r.Brand.Brand_ID == brand
                   orderby s.STATE_ABBR
                   select s;
Run Code Online (Sandbox Code Playgroud)

当然,这不会急切地加载REGION(s),所以你可能认为你可以这样写:

var productQuery = from s in LeadsContext.State.Include("REGION")
                   from r in s.REGION
                   where r.Brand.Brand_ID == brand
                   orderby s.STATE_ABBR
                   select s;
Run Code Online (Sandbox Code Playgroud)

但这不起作用,因为当你选择多个(即from y in z from x in y)时你的INCLUDE会丢失.

所以你必须在最后做这样的包括:

var productQuery = (from s in LeadsContext.State
                   from r in s.REGION
                   where r.Brand.Brand_ID == brand
                   orderby s.STATE_ABBR
                   select s) as ObjectQuery<State>).Include("REGION");
Run Code Online (Sandbox Code Playgroud)

有关此变通方法的更多信息,请参阅技巧22

我不是100%确定我们的查询构建器方法,即Where(字符串),支持子选择哪个是必需的.

所以我不确定那里的语法是什么.

无论如何,我希望这有帮助

亚历克斯


小智 6

Alex,您可以通过以不同方式处理查询来在查询构建器中实现类似的功能.查询构建器支持存在.查询将如下所示:

 ObjectQuery productQuery = 
        LeadsContext.STATE.Include("REGION")
          .Where("EXISTS(SELECT 1 FROM it.REGION.BRAND as b WHERE b.BRAND_ID
= @brand)", new ObjectParameter("brand", brand))
          .OrderBy("it.STATE_ABBV");