LINQ TO ENTITY无法与枚举类型进行比较

时间:2018-05-27 10:14:42

标签: c# asp.net-mvc entity-framework enums linq-to-entities

以下是enum Leaves

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

以下是linq查询

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

我甚至尝试使用Leaves.Annual,但它不起作用。 LINQ QUERY THROWS如果出现异常:

  

System.NotSupportedException HResult = 0x80131515 Message =无法创建类型' System.Object'的常量值。在此上下文中仅支持原始类型或枚举类型。

2 个答案:

答案 0 :(得分:2)

Linq2ToEntity不支持

Equals你应该使用双等号:

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

假设你的Profileid是一个使用==的int,应该让它在不改变逻辑或遇到案例问题的情况下工作。

答案 1 :(得分:1)

问题与Enum类型无关。您不能将Equals用于Linq实体。所以,修改你的查询;

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