Search code examples
c#asp.net-mvcentity-frameworkenumslinq-to-entities

LINQ TO ENTITY cannot compare to enumeration types


Below are the enum Leaves

public enum Leaves
{
    Annual = 0,
    Medical = 1,
    Hospitalization = 2,
    Unpaid = 3
}

Below is the linq query

public ActionResult ApproveLeave(int? id)
    {
        if (id == null)
            return View();

        LeaveApplication leaveApplication = db.LeaveApplication.Find(id);

        if (leaveApplication == null)
            return HttpNotFound();

        leaveApplication.Status = "Approved";

        if (ModelState.IsValid)
        {
            db.Entry(leaveApplication).State = EntityState.Modified;

            Leaves leavesType = (Leaves)Enum.Parse(typeof(Leaves), leaveApplication.LeaveType.ToString());

            var lb = (from t in db.LeaveBalance
                      select t)
                      .Where(t => t.LeaveType == leavesType && t.Profileid.Equals(id))
                      .FirstOrDefault();

            lb.Taken++;
            lb.Balance--;
            db.SaveChanges();

            return RedirectToAction("Index");
        }

        return View();
    }

I have even try using the Leaves.Annual but it doesnt work. LINQ QUERY THROWS FOLLOWING EXCEPTION :

System.NotSupportedException HResult=0x80131515 Message=Unable to create a constant value of type 'System.Object'. Only primitive types or enumeration types are supported in this context.


Solution

  • Equals is not supported in Linq2ToEntity you should use the double equal instead:

    var lb = (from t in db.LeaveBalance select t)
      .Where(t => t.LeaveType == leavesType && t.Profileid == id)
      .FirstOrDefault();
    

    Assuming that your Profileid is a int using the == should make it work without changing the logic or running into case issues.