簡體   English   中英

EF CORE LINQ 日期與 new DateTime(yearId, monthId, dateId) 的比較

[英]EF CORE LINQ date comparison with new DateTime(yearId, monthId, dateId)

我正在嘗試對 EF 上下文中的DbSet執行 LINQ 查詢。 LastDAyToEnterData類中的DbSet類有3 個short 類型的get/set 屬性,映射到一個SQL Server 表,其中3 列分別為年、月、日的smallint類型。 當我在.Where()使用表達式時,出現此錯誤。 我應該使用什么表達式來比較兩個日期? 謝謝。

無法翻譯 LINQ 表達式。 以可翻譯的形式重寫查詢,或通過插入對 AsEnumerable()、AsAsyncEnumerable()、ToList() 或 ToListAsync() 的調用顯式切換到客戶端評估。 有關詳細信息,請參閱https://go.microsoft.com/fwlink/?linkid=2101038

DbSet<LastDayToEnterData>
    .Where(l => new DateTime(
        (int)l.YearID, 
        (int)l.MonthID, 
        (int)l.StopEnteringDataAfter
    ) > new DateTime(
        DateTime.Today.Year - 1, 
        10, 
        1
    ))

您需要使用DbFunctions.CreateDateTime來創建新的 DateTime 對象,並從 Linq 中投射出比較日期:

var compareDate = new DateTime(DateTime.Today.Year - 1, 10, 1);

DbSet<LastDayToEnterData>
    .Where(l => EntityFunctions.CreateDateTime(
        (int)l.YearID, 
        (int)l.MonthID, 
        (int)l.StopEnteringDataAfter
    ) > compareDate )

無法翻譯 LINQ 表達式。 以可翻譯的形式重寫查詢,或通過插入對 AsEnumerable()、AsAsyncEnumerable()、ToList() 或 ToListAsync() 的調用顯式切換到客戶端評估。 有關詳細信息,請參閱https://go.microsoft.com/fwlink/?linkid=2101038

原因是隱式客戶端評估已在 EF Core 3 中禁用。

參考:

https://docs.microsoft.com/en-us/ef/core/what-is-new/ef-core-3.0/break-changes#linq-queries-are-no-longer-evaluated-on-the-客戶

作為一種解決方法,您可以進行如下更改:

1.型號:

public class LastDayToEnterData
{
    public int Id { get; set; }
    public int YearID { get; set; }
    public int MonthID { get; set; }
    public int StopEnteringDataAfter { get; set; }
    public string Name { get; set; }
}

2.控制器:

var date = _context.LastDayToEnterData.Select(u => new { u.MonthID, u.YearID, u.StopEnteringDataAfter,u.Id }).ToList();
var list = new List<LastDayToEnterData>();
foreach(var d in date)
{
    var ConvertDate = new DateTime(d.YearID,d.MonthID, d.StopEnteringDataAfter);
    if(ConvertDate > new DateTime(DateTime.Today.Year - 1, 10, 1))
    {
        var data = _context.LastDayToEnterData
                           .Where(l => d.Id == l.Id).FirstOrDefault();
        list.Add(data);
    }               
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM