简体   繁体   English

Linq to EF查询,带条件过滤器

[英]Linq to EF query with criteria filter

I have two tables - below as seen in database 我有两个表-如数据库中所示

| | Country | 国家(地区)| ID int | ID int | Name varchar | 名称varchar |

| | Car |ID int | 车| ID int | Name varchar | 名称varchar | CountryID int FK to Country CountryID int FK到国家

  1. I need to select all the Cars in country with ID 1 我需要选择ID为1的国家/地区的所有汽车

  2. I also need all the cars in countries WITH ID 2 and 3 whos ids(car) are in (4,5) 我还需要ID为2和3的国家/地区的所有汽车,谁的id(car)在(4,5)

Using EF i have the below query. 使用EF我有以下查询。

       List<int> listOfCountries = new List<int> { 1,2,3 };

        var query = (
            from country in context.Countries.AsNoTracking()
            join car in context.Cars.AsNoTracking() on new { CountryID = country.ID}
                            equals new { CountryID = cars .CountryID } 
            where listOfCountries.Contains(prv.CountryID)
            select car);

Is there any other way to do this instead of using a union? 还有其他方法可以代替工会使用吗? Do i need a case statement eg when country id not equal to (1) then filter where car id in (4,5), how is this achieved? 我是否需要一个案例说明,例如,当国家/地区ID不等于(1),然后过滤(4,5)中的汽车ID时,该如何实现? Thanks. 谢谢。

If i understand your question correctly, this could be it: 如果我正确理解您的问题,可能是这样:

List<int> listOfCountries = new List<int> { 2,3 };
List<int> listOfCarIds = new List<int> { 4,5 };

var query = from car in context.Cars.AsNoTracking()
where car.Country.Id = 1 || (listOfCountries.Contains(car.Country.Id) && listOfCarIds.Contains(car.Id))

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

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