【发布时间】:2020-05-06 23:50:25
【问题描述】:
我有一个查询来列出一组名为 Transaction with children 的实体。当尝试应用 where 来过滤子项中的道具时,它会引发 Linq 无效操作。 (EF 核心)
代码如下:
var query = DataContext.Transactions
.Select(x => new Transaction
{
Id = x.Id,
TotalAmount = x.TotalAmount,
CreatedAt = x.CreatedAt,
TransactionState = x.TransactionState == null ? null :
new TransactionState
{
Id = x.TransactionState.Id,
Name = x.TransactionState.Name
},
Beneficiary = x.Beneficiary == null ? null :
new Beneficiary
{
Id = x.Beneficiary.Id,
DocumentNumber = x.Beneficiary.DocumentNumber
}
})
.AsNoTracking()
.AsQueryable();
if (!filter.IsNullEmtpyOrWhiteSpace()) // Own Property
{
// This is the line where apply where in prop
query = query.Where(x => x.Beneficiary != null && x.Beneficiary.DocumentNumber.Contains(filter));
}
var count = query.Count();
if (take > 0) query = query.Skip(skip).Take(take);
return new ListAndCountDto<Transaction>
{
Data = query.ToList(),
Count = count
};
这是错误异常:
"The LINQ expression 'DbSet<Transaction>\n
.LeftJoin(\n outer: DbSet<Beneficiary>, \n
inner: t => EF.Property<Nullable<int>>(t,
\"BeneficiaryId\"), \n outerKeySelector: b => EF.Property<Nullable<int>>(b, \"Id\"), \n
innerKeySelector: (o, i) => new TransparentIdentifier<Transaction, Beneficiary>(\n
Outer = o, \n Inner = i\n ))\n .Where(t => EF.Property<Nullable<int>>(t.Inner, \"Id\") == null ?
null : new Beneficiary{ \n Id = t.Inner.Id, \n DocumentNumber = t.Inner.DocumentNumber \n }\n
!= null && EF.Property<Nullable<int>>(t.Inner, \"Id\") == null ? null : new Beneficiary{ \n
Id = t.Inner.Id, \n DocumentNumber = t.Inner.DocumentNumber \n }\n
.DocumentNumber.Contains(__filter_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."
【问题讨论】:
标签: c# linq lambda entity-framework-core expression