Only primitive types or enumeration types are supported in this context

c# entity-framework linq

Question

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?

1
9
5/17/2013 6:43:52 PM

Accepted Answer

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.

14
5/17/2013 6:42:40 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow