gpt4 book ai didi

c# - 创建用于 Entity Framework 6 的表达式

转载 作者:行者123 更新时间:2023-12-04 09:38:05 25 4
gpt4 key购买 nike

我有以下方法启动 IQueryable .

public static IQueryable<StorageDetail> QueryStorageDetails(ApplicationDbContext dbContext, DateRange dateRange)
{
return from detail in dbContext.StorageDetails
where (detail.ArrivalDate != null && detail.ArrivalDate <= dateRange.EndDate &&
(detail.ReleaseDate == null || detail.ReleaseDate >= dateRange.StartDate)) ||
(detail.TakeOrPayStartDate != null && detail.TakeOrPayStartDate <= dateRange.EndDate &&
(detail.TakeOrPayEndDate == null || detail.TakeOrPayEndDate >= dateRange.StartDate))
select detail;
}

我尝试如下重构它。
public static bool FilterByDate(StorageDetail detail, DateRange dateRange)
{
return (detail.ArrivalDate != null && detail.ArrivalDate <= dateRange.EndDate &&
(detail.ReleaseDate == null || detail.ReleaseDate >= dateRange.StartDate)) ||
(detail.TakeOrPayStartDate != null && detail.TakeOrPayStartDate <= dateRange.EndDate &&
(detail.TakeOrPayEndDate == null || detail.TakeOrPayEndDate >= dateRange.StartDate));
}

public static IQueryable<StorageDetail> QueryStorageDetails(ApplicationDbContext dbContext, DateRange dateRange)
{
return dbContext.StorageDetails
.Where(d => FilterByDate(d, dateRange));
}

但这会产生错误。
The LINQ expression 'DbSet<StorageDetail>
.Where(s => QueryHelper.FilterByDate(
detail: s,
dateRange: __dateRange_0))' could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to either AsEnumerable(), AsAsyncEnumerable(), ToList(), or ToListAsync(). See https://go.microsoft.com/fwlink/?linkid=2101038 for more information.

我很确定有一种方法可以做到这一点,可能是通过创建一个 Expression但我似乎无法正确使用语法。有人知道怎么做吗?

最佳答案

FilterByDate应该返回 Expression<Func<StorageDetail, bool>>因此 EF 将能够将您的代码转换为查询。尝试这样的事情:

public static Expression<Func<StorageDetail, bool>> FilterByDate(DateRange dateRange)
{
return detail => (detail.ArrivalDate != null && detail.ArrivalDate <= dateRange.EndDate &&
(detail.ReleaseDate == null || detail.ReleaseDate >= dateRange.StartDate)) ||
(detail.TakeOrPayStartDate != null && detail.TakeOrPayStartDate <= dateRange.EndDate &&
(detail.TakeOrPayEndDate == null || detail.TakeOrPayEndDate >= dateRange.StartDate));
}


public static IQueryable<StorageDetail> QueryStorageDetails(ApplicationDbContext dbContext, DateRange dateRange)
{
return dbContext.StorageDetails
.Where(FilterByDate(dateRange));
}

关于c# - 创建用于 Entity Framework 6 的表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62458430/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com