LINQ to Entity选择查询错误

时间:2013-01-11 07:59:26

标签: c# linq select entity

using (SmartEntities employeeverificationcontext = new SmartEntities())
{
    Employee emp = (from c in employeeverificationcontext.EmployeeEntity 
                    where c.Employee_ID == emp_detail.EmployeeID 
                    select new Employee {c.Status}).FirstOrDefault();
    emp.Status = emp_detail.Status;
    int i=employeeverificationcontext.SaveChanges();
    if (i > 0)
    {
        result = "Verification Process Completed";
    }
}
  

错误:错误1无法使用集合初始值设定项初始化类型'SmartWCF.Employee',因为它没有实现'System.Collections.IEnumerable'**

2 个答案:

答案 0 :(得分:1)

您应该选择当前对象(select new Employee {c.Status}

而不是c

所以你的查询应该是:

Employee emp = (from c in employeeverificationcontext.EmployeeEntity 
               where c.Employee_ID == emp_detail.EmployeeID 
               select c).FirstOrDefault();

Employee emp = employeeverificationcontext.EmployeeEntity
                      .FirstOrDefault(c=> Employee_ID == emp_detail.EmployeeID);

答案 1 :(得分:0)

只选择Status,如下所示:

var employeeStatus = (from c in employeeverificationcontext.EmployeeEntity 
                        where c.Employee_ID == emp_detail.EmployeeID 
                      select c.Status).FirstOrDefault();

但是如果您想将其设置为新状态并将其保存到数据上下文中,这对您没有帮助。在这种情况下,您必须选择Employee

本文中提到了一些替代方案:How to update a single column in LINQ without loading the entire row?