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

lol*_*pop 5 c# asp.net-mvc enums linq-to-entities entity-framework

下面是枚举叶子

public enum Leaves
{
    Annual = 0,
    Medical = 1,
    Hospitalization = 2,
    Unpaid = 3
}
Run Code Online (Sandbox Code Playgroud)

下面是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();
    }
Run Code Online (Sandbox Code Playgroud)

我什至尝试使用 Leaves.Annual 但它不起作用。LINQ 查询抛出以下异常:

System.NotSupportedException HResult=0x80131515 Message=无法创建“System.Object”类型的常量值。此上下文中仅支持基本类型或枚举类型。

小智 4

EqualsLinq2ToEntity 不支持您应该使用双等号代替:

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

假设您的 Profileid 是一个使用 == 的 int 应该可以使其工作而无需更改逻辑或遇到大小写问题。