这使我今天无法解决问题。我有这个简单的查询
var result =
DataContext.Accommodations.Where(a =>
(criteria.MinPrice == null || a.AccommodationRates.Any(r => r.From >= criteria.MinPrice)) &&
(criteria.MaxPrice == null || a.AccommodationRates.Any(r => r.To <= criteria.MaxPrice)) &&
(criteria.Locations == null || criteria.Locations.Count == 0 || a.AccommodationPlaceJoins.Any(j => criteria.Locations.Contains(j.Place.PlaceName)))
);
此查询的最后一行导致我出现问题
(criteria.Locations == null ||
criteria.Locations.Count == 0 ||
a.AccommodationPlaceJoins.Any(j => criteria.Locations.Contains(j.Place.PlaceName)))
它给出的错误是
无法创建类型的常量值 'System.Collections.Generic.IList`1'。只有原始类型('如 在此上下文中支持Int32,String和Guid'。
我甚至没有尝试创建列表。我在这里尝试做的就是带回与一个地方相关的住宿(Place表中通过AccommodationPlaceJoin表链接到住宿表的地名)等于标准中的任何一个地名.Locations(属于IList类型)。
我已尝试将此行更改为此行,但它无效。
(criteria.Locations == null ||
criteria.Locations.Count == 0 ||
a.AccommodationPlaceJoins.Any(j => criteria.Locations.Any(l => l == j.Place.PlaceName)))
答案 0 :(得分:36)
对于null
,比较criteria.Locations == null
的常量值EF无法创建var result = DataContext.Accommodations.Where(a =>
(criteria.MinPrice == null ||
a.AccommodationRates.Any(r => r.From >= criteria.MinPrice)) &&
(criteria.MaxPrice == null ||
a.AccommodationRates.Any(r => r.To <= criteria.MaxPrice)));
if (criteria.Locations != null && criteria.Locations.Count > 0)
{
result = result.Where(a => a.AccommodationPlaceJoins
.Any(j => criteria.Locations.Contains(j.Place.PlaceName)));
}
。您需要将查询拆分为两种情况,并检查查询外的空列表,例如:
IQueryable<Accommodation> result = DataContext.Accommodations;
if (criteria.MinPrice != null)
result = result.Where(a => a.AccommodationRates
.Any(r => r.From >= criteria.MinPrice));
if (criteria.MaxPrice != null)
result = result.Where(a => a.AccommodationRates
.Any(r => r.To <= criteria.MaxPrice));
if (criteria.Locations != null && criteria.Locations.Count > 0)
result = result.Where(a => a.AccommodationPlaceJoins
.Any(j => criteria.Locations.Contains(j.Place.PlaceName)));
修改强>
BTW:在我看来,编写整个查询会使其更易读,并且会简化必须发送到数据库的SQL:
{{1}}