Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Only primitive types or enumeration types are supported in this context

So I have this code:

    public int saleCount(List<Shift> shifts) {
        var query = (
            from x in database.ItemSales
            where shifts.Any(y => y.ID == x.shiftID)
            select x.SalesCount
        );
        return query.Sum();
    }

Unfortunately, it's throwing this error:

Unable to create a constant value of type 'Shift'. 
Only primitive types or enumeration types are supported in this context.

So here is where I define shift, which is just a normal Entity Framework Code First object:

[Table("Shifts")]
public class Shift : MPropertyAsStringSettable {
    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public int ID { get; set; }
    public int SiteID { get; set; }
    public string ShiftID_In_POS { get; set; }
    public DateTime ShiftDate { get; set; }
}

I guess the problem is that I am using Shift object in a Linq query. And I am doing a "Any" operation on a List of "Shift".

One possible solution is to change the List to maybe a Collection or something, afterall, I am loading it with a linq query somewhere else, but what would the signature be?

like image 616
Bill Software Engineer Avatar asked May 17 '13 18:05

Bill Software Engineer


1 Answers

Try this change that does not use a collection of Shifts in the query:

public int saleCount(List<Shift> shifts) {
    var shiftIds = shifts.Select(s => s.ID).ToList();
    var query = (
        from x in database.ItemSales
        where shiftIds.Contains(x.shiftID)
        select x.SalesCount
    );
    return query.Sum();
}

The idea is to avoid passing Shift objects to the query provider, using IDs instead.

like image 75
Sergey Kalinichenko Avatar answered Nov 16 '22 02:11

Sergey Kalinichenko