Entity Framework: Unable to create a constant value of type 'System.Collections.Generic.IList`1'

前端 未结 1 1037
心在旅途
心在旅途 2020-12-29 08:42

This has caused me no end of problems today. I have this simple query

var result =
    DataContext.Accommodations.Where(a => 
        (criteria.MinPrice          


        
相关标签:
1条回答
  • 2020-12-29 09:47

    The constant value EF can't create is null for the comparison criteria.Locations == null. You need to split the query into two cases and do the check for the empty list outside of the query, for example like so:

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

    Edit

    BTW: Composing the whole query would make it better readable in my opinion and will simplify the SQL that has to be sent to the database:

    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)));
    
    0 讨论(0)
提交回复
热议问题