【问题标题】:Linq to EF query with criteria filter带有条件过滤器的 Linq to EF 查询
【发布时间】:2016-06-06 06:14:59
【问题描述】:

我有两个表 - 如下数据库中所示

|国家 | ID 整数 |名称 varchar |

|汽车 |ID int |名称 varchar | CountryID int FK 到国家/地区

  1. 我需要选择 ID 为 1 的国家/地区的所有汽车

  2. 我还需要 ID 为 2 和 3 的国家/地区的所有汽车,他们的 ID(汽车)在 (4,5) 中

使用 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);

除了使用联合之外,还有其他方法可以做到这一点吗?我是否需要一个案例陈述,例如当国家 ID 不等于 (1) 然后过滤 (4,5) 中的汽车 ID 时,这是如何实现的?谢谢。

【问题讨论】:

  • 不就是 WHERE 中的 OR 语句吗?

标签: c# sql linq entity-framework-5


【解决方案1】:

如果我正确理解您的问题,可能是这样:

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))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多