我有以下控制器动作方法
public ActionResult BondCompletion(DateTime? ToDate)
{
List<BondCompletionViewModel> bondCompletionViewModel = new List <BondCompletionViewModel>();
if (ToDate != null)
{
bondCompletionViewModel = db.Employees.Select(y => new
{
y.JoiningDate ,
y.Commitments ,
y.EmployeeId ,
y.Name
})
.Where(x => x.JoiningDate.AddMonths(x.Commitments.Value).Month == ToDate.Value.Month)
.Select(z => new BondCompletionViewModel
{
EmployeeId = z.EmployeeId.Value,
EmployeeName = z.Name,
StartDate = z.JoiningDate,
EndDate = z.JoiningDate//.AddMonths(x.Commitments.Value)
}).ToList();
}
return View(bondCompletionViewModel);
}
Run Code Online (Sandbox Code Playgroud)
在上面的方法中,Commitments是nullable int,JoiningDate是datetime.当我运行此如果显示以下错误
" LINQ to Entities无法识别方法'System.DateTime AddMonths(Int32)'方法,并且此方法无法转换为存储表达式."
请指导我如何解决此错误.
你的问题不是linq.您的问题是EF不知道如何将该语句(z.JoiningDate.AddMonths(x.Commitments.Value))转换为SQL.
如果你选择ToList()之前它应该工作.
否则你应该使用
EntityFunctions.AddMonths(z.JoiningDate, x.Commitments.Value)
Run Code Online (Sandbox Code Playgroud)
哪个EF确实可以转换为SQL
换一种说法
.Select(z => new BondCompletionViewModel
{
EmployeeId = z.EmployeeId.Value,
EmployeeName = z.Name,
StartDate = z.JoiningDate,
EndDate = EntityFunctions.AddMonths(z.JoiningDate, x.Commitments.Value)
}).ToList();
Run Code Online (Sandbox Code Playgroud)
编辑: DbFunctions是要使用的新EF 6类而不是EntityFunctions
| 归档时间: |
|
| 查看次数: |
2096 次 |
| 最近记录: |