英文:
Is there any chance to call Expression in Linq (Entity Framework)
问题
我正在尝试在 Entity Framework 中的 LINQ 表达式中使用筛选器。我的函数是:
```cs
private static DateTime GetLastDayOfQuarter(DateTime dateTime)
{
return new DateTime(dateTime.Year, dateTime.Month + 3 - dateTime.Month % 3, DateTime.DaysInMonth(dateTime.Year, dateTime.Month + 3 - dateTime.Month % 3));
}
查询:
var taskDto = await (
from task in dbContext.TbTasks
join tu in dbContext.TbTaskUsers on task.Id equals tu.Taskid
join tt in dbContext.TbTaskTypes on task.Tasktypeid equals tt.Id
where tu.Customercode == customerCode &&
task.Startdate < DateTime.Now &&
((task.Enddate > DateTime.Now && tu.Status == 0) || (task.Tasktypeid == 4 && task.Giftcount >= 50 && DateTime.Now < GetLastDayOfQuarter(task.Enddate)))
select new CustomerTaskDto()
{
ResponseTime = tu.Responsetime,
TaskPeriod = $"{task.Createdate} - {task.Enddate}",
TaskType = tt.Id == 4 && task.Giftcount >= 50 ? "Süper Yap Kazan" : tt.Name,
TaskTypeId = tt.Id,
EndDate = task.Enddate,
TaskId = task.Id
}).ToListAsync();
return taskDto;
我尝试在 WHERE 子句中调用函数、表达式等,但没有解决异常。是否有可能调用它?
<details>
<summary>英文:</summary>
I am trying to use filter in the linq expression in Entity Framework. My function is:
```cs
private static DateTime GetLastDayOfQuarter(DateTime dateTime)
{
return new DateTime(dateTime.Year, dateTime.Month + 3 - dateTime.Month % 3, DateTime.DaysInMonth(dateTime.Year, dateTime.Month + 3 - dateTime.Month % 3));
}
Query:
var taskDto = await (
from task in dbContext.TbTasks
join tu in dbContext.TbTaskUsers on task.Id equals tu.Taskid
join tt in dbContext.TbTaskTypes on task.Tasktypeid equals tt.Id
where tu.Customercode == customerCode && task.Startdate < DateTime.Now &&
((task.Enddate > DateTime.Now && tu.Status == 0) || (task.Tasktypeid == 4 && task.Giftcount >= 50 && DateTime.Now < GetLastDayOfQuarter(task.Enddate)))
select new CustomerTaskDto()
{
ResponseTime = tu.Responsetime,
TaskPeriod = $"{task.Createdate} - {task.Enddate}",
TaskType = tt.Id == 4 && task.Giftcount >= 50 ? "Süper Yap Kazan" : tt.Name,
TaskTypeId = tt.Id,
EndDate = task.Enddate,
TaskId = task.Id
}).ToListAsync();
return taskDto;
I tried to call function, expression or etc on the where clause. Nothing solved the exception. Is there any possibility to call it?
答案1
得分: 1
Entity Framework 在查询之前必须将你的代码转换为 TSQL 代码,因此它无法翻译复杂的表达式。
唯一的方法是将原始数据提取到一个 List
中,然后使用 LINQ to Objects 应用任何你喜欢的过滤条件。
英文:
Entity Framework will have to translate your code into TSQL code before querying. Thus, it can't translate complex expressions.
The only way you can achieve that is by fetching rough data into a List
and then apply whatever the filtering conditions you like with LINQ to Objects.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论