【发布时间】:2020-12-02 11:09:37
【问题描述】:
我使用 .Net 5 和 Entity Freamwork Core 编写应用程序。 我有正在寻找一些数据的方法。 它看起来像这样:
public async Task<Result<List<Company>>> Search(string keyword, DateTime From, DateTime To, JobTitle jobTitle)
{
return Result.Ok(await _dataContext.Companies
.Include(x => x.Employes
.WhereIf(From != default && To != default,
x => x.DateOfBirth >= From && x.DateOfBirth <= To && x.JobTitle == jobTitle))
.WhereIf(!string.IsNullOrEmpty(keyword),
x => x.Name.Contains(keyword))
.ToListAsync());
}
WhereIf 看起来像这样:
public static class LinqExtension
{
public static IQueryable<TSource> WhereIf<TSource>(this IQueryable<TSource> source, bool condition, Expression<Func<TSource, bool>> predicate)
{
if (condition)
return source.Where(predicate);
return source;
}
public static IEnumerable<TSource> WhereIf<TSource>(this IEnumerable<TSource> source, bool condition, Func<TSource, bool> predicate)
{
if (condition)
return source.Where(predicate);
return source;
}
}
当我使用这种方法时,我得到了这个错误:
System.InvalidOperationException: The expression 'x.Employes.WhereIf(__p_0, x => (((x.DateOfBirth >= __From_1) AndAlso (x.DateOfBirth <= __To_2)) AndAlso (Convert(x.JobTitle, Int32) == Convert(__jobTitle_3, Int32))))' is invalid inside an 'Include' operation, since it does not represent a property access: 't => t.MyProperty'. To target navigations declared on derived types, use casting ('t => ((Derived)t).MyProperty') or the 'as' operator ('t => (t as Derived).MyProperty'). Collection navigation access can be filtered by composing Where, OrderBy(Descending), ThenBy(Descending), Skip or Take operations. For more information on including related data
如何解决这个错误?
【问题讨论】:
标签: .net entity-framework asp.net-core entity-framework-core