Bill Software Engineer
Bill Software Engineer

Reputation: 7782

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?

Upvotes: 11

Views: 28114

Answers (2)

Sumit Singh
Sumit Singh

Reputation: 1258

I am getting this error because

bool isPresent = entities.VaccinationRecords.Any(id => id.PersonId.equals(studetails.StuId));

personID and StuId is INT type , but I am using .equals to compare both values.

Then i have done this;

bool isPresent = entities.VaccinationRecords.Any(id => id.PersonId == studetails.StuId);

Issue resolved.

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726479

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.

Upvotes: 18

Related Questions