简体   繁体   English

实体框架基于跨多个子集合的过滤器的选择对象

[英]Entity Framework select object based on filters accross multiple child collections

Assume I have the following domain (not my actual domain, but a trivial example) 假设我拥有以下域(不是我的实际域,而是一个简单的示例)

public class ClassRoom
{
  public int Id {get;set;}
  public string Name {get;set;}
  public virtual ICollection<Desk> Desks{get;set;}
  public virtual ICollection<LunchBox> LunchBoxs{get;set;}
}

public class Desk
{
  public int Id {get;set;}
  public String Colour {get;set;}
  public String Make {get;set;}
  Public ClassRoom ClassRoom {get;set;}
}

public class LunchBox
{
  public int Id {get;set;}
  public String Colour {get;set;}
  public int Volume {get;set;}
}

I would like to be able to query as follows 我希望能够如下查询

"Give me all the classes that have blue desks or green lunchboxes" returning a list of classes “给我所有有蓝色书桌或绿色午餐盒的课程”,返回课程列表

I would have thought the code to be 我本以为代码是

var efClasses = (from d in myentity.ClassRooms
                  where ( (d.Desks.Colour == "blue")
                         || (d.LunchBoxs.Colour == "green) )
select d).Distinct();

doing this gives me the error 这样做给我错误

Cannot convert lambda expression to type 'string' because it is not a delegate type (obviously unhappy about the Colour, it expects a method here 无法将lambda表达式转换为“字符串”类型,因为它不是委托类型(显然对颜色不满意,它期望在此处使用一种方法

so I changed it to this as an experiment 所以我把它改成了实验

var efClasses = (from d in myentity.ClassRoom
                  where ( (d.Desks.Where(x=>x.Colour == "blue"))
                         || (d.LunchBoxs.Where(x=>x.Colour == "green)) )
select d).Distinct();

But this wont compile either (In hindsight I had a feeling I was trying my luck on this. 但这也不会编译(事后看来,我有一种运气。

I could go the other way around by changing my from to be myentity.Desks, and myEntity.Lunchboxs, and return two seperate lists of ClassRooms, and then find the union, but this will require 2 separate DB hits, and feels hacky 我可以通过将my更改为myentity.Desks和myEntity.Lunchboxs,然后返回两个单独的ClassRooms列表,然后找到并集,来进行另一种方法,但这将需要2次单独的数据库命中,并且感觉很hack

Instead of using count > 0, you can use Any 代替使用count> 0,可以使用Any

var efClasses = (from d in myentity.ClassRoom
                 where (d.Desks.Any(x => x.Colour == "blue") ||
                        d.LunchBoxs.Any(x => x.Colour == "green"))
                 select d);

Use Count >0 like this. 像这样使用Count> 0。

 var efClasses = (from d in myentity.ClassRoom
                             where (d.Desks.Count(x => x.Colour == "blue") > 0
                                    || d.LunchBoxs.Count(x => x.Colour == "green") > 0)
                             select d);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM