我有一个DateTime对象列表(本地列表(,我想在EF核心的查询中使用它,如下所示:
var teacher = _appDataContext
.Teachers
.AsExpandable()
.Where(x => x.Id.Equals(booking.Teacher.Id))
.Select(x => new
{
IsConflicted = x
.Bookings
.Any(y => booking.StartingTimes.Any(z => y.StartingTime <= z && z < y.EndingTime)) // booking.StartingTimes is a local list.
})
.FirstOrDefault();
但每当我运行代码时,它都会给我以下错误:
System.InvalidOperationException: The LINQ expression 'DbSet<Booking>
.Where(b0 => EF.Property<Nullable<Guid>>((EntityShaperExpression:
EntityType: Teacher
ValueBufferExpression:
(ProjectionBindingExpression: Outer.Outer)
IsNullable: False
), "Id") != null && EF.Property<Nullable<Guid>>((EntityShaperExpression:
EntityType: Teacher
ValueBufferExpression:
(ProjectionBindingExpression: Outer.Outer)
IsNullable: False
), "Id") == EF.Property<Nullable<Guid>>(b0, "TeacherId"))
.Any(b0 => __booking_StartingTimes_4
.Any(z => b0.StartingTime <= z && z < b0.EndingTime))' 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.
这是否意味着我不能在本地列表中进行这种比较?还有其他方法可以实现我想要做的事情吗?
所以我能够解决这个问题。然而,我的解决方案需要添加LinqKit
包:
首先,我通过在本地StartingTimes
上循环来逐步构建一个谓词,如下所示:
Expression<Func<Booking, bool>> predicate = x => false;
booking.StartingTimes.ToList().ForEach(x => { predicate = predicate.Or(y => y.StartingTime <= x && x < y.EndingTime); });
之后,我只是使用谓词作为Any
方法的参数,如下所示:
var teacher = _appDataContext
.Teachers
.AsExpandable()
.Where(x => x.Id.Equals(booking.Teacher.Id))
.Select(x => new
{
IsConflicted = x
.Bookings
.Any(predicate.Invoke())
})
.FirstOrDefault();