EF - 如何使用linq编辑以下模型?

时间:2013-04-01 09:26:21

标签: c# .net linq entity-framework

我正在从客户端发送一些视图模型数据,并希望更新模型。我知道如何通过调用存储过程来做到这一点,但非常想知道如何使用linq查询来做到这一点。任何帮助将不胜感激。感谢

[HttpPost]
         public JsonResult EditEmployee(Models.Employee employee) 
         {
             try
             {
                 if (ModelState.IsValid)
                 {
                     using (emsCtx)
                     {
                         var employeeResults = (from q in emsCtx.Employees
                                                where q.Id == employee.Id
                                                //code to update the model.
                                                );                    
                               employeeData.Employees = employeeResults;         
                     }

                     return Json();
                 }

1 个答案:

答案 0 :(得分:1)

如果您要更新数据库中与员工相对应的数据,请在下面检查您编辑的代码:

     [HttpPost]
     public JsonResult EditEmployee(Models.Employee employee) 
     {
         try
         {
             if (ModelState.IsValid)
             {
                 using (emsCtx)
                 {
                     var employeeResults = (from q in emsCtx.Employees
                                            where q.Id == employee.Id
                                             select q
                                            ).FirstOrDefault();        
                     if(employeeResults!=null)
                     {             
                           employeeResults.Column1 = employee.Column1; 
                           employeeResults.Column2 = employee.Column2; 
                           employeeResults.Column3 = employee.Column3; 
                           employeeResults.Column4 = employee.Column4; 
                     }
                     emsCtx.SaveChanges();
                 }

                 return Json();
             }