簡體   English   中英

包含不能翻譯 EF .net 核心 3.1

[英]contains cannot not be translate EF .net core 3.1

您好,我嘗試像這樣對 EF 3.1 進行查詢:

  Expression<Func<MedicalResponsibleWard, bool>> predicate = x => x.InstitutionId == request.InstitutionId;
        if (request.GroupId != null)
            predicate = predicate.AndAlso(x => x.GroupId == request.GroupId);
        if (request.Code != null)
            predicate = predicate.AndAlso(x => x.Code == request.Code);
       
            if (request.MedicalResponsibleWarName != null)
                predicate = predicate.AndAlso(x => x.Properties.Any(m => m.Name.Contains(request.MedicalResponsibleWarName, StringComparison.InvariantCultureIgnoreCase)));

        return (await _genericRepository.GetAsync(predicate, query => query.Include(c => c.Properties)))
         .OrderBy(g => g.Id).ToList();

但是轉換失敗是因為這個謂詞

if (request.MedicalResponsibleWarName != null)
            predicate = predicate.AndAlso(x => x.Properties.Any(m => m.Name.Contains(request.MedicalResponsibleWarName, StringComparison.InvariantCultureIgnoreCase)));

錯誤是

The LINQ expression 'DbSet<MedicalResponsibleWardProperty>
.Where(m0 => EF.Property<Nullable<int>>((EntityShaperExpression: 
    EntityType: MedicalResponsibleWard
    ValueBufferExpression: 
        (ProjectionBindingExpression: EmptyProjectionMember)
    IsNullable: False
), "Id") != null && EF.Property<Nullable<int>>((EntityShaperExpression: 
    EntityType: MedicalResponsibleWard
    ValueBufferExpression: 
        (ProjectionBindingExpression: EmptyProjectionMember)
    IsNullable: False
), "Id") == EF.Property<Nullable<int>>(m0, "MedicalResponsibleWardId"))
.Any(m0 => m0.Name.Contains(
    value: __request_MedicalResponsibleWarName_1, 
    comparisonType: InvariantCultureIgnoreCase))' 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.

請問怎么解決? 問候

以可翻譯的形式重寫查詢,或通過插入對 AsEnumerable()、AsAsyncEnumerable()、ToList() 或 ToListAsync() 的調用顯式切換到客戶端評估

問題在解釋中提到,這種查詢需要客戶端評估,默認關閉。 服務器端不支持這種類型的評估,因為它需要將實體加載到 memory 並過濾大量數據,這可能會導致性能不佳。 有關更多詳細信息,請參閱不支持的客戶端評估

實際上,我經歷了這個問題,並按照Microsoft docs 的建議使用第三方 nuget 找到了更好的方法。 下載並安裝LinqKit ,然后您可以使用動態組合表達式謂詞

IQueryable<Product> SearchProducts (params string[] keywords)
{
  var predicate = PredicateBuilder.False<Product>();

  foreach (string keyword in keywords)
    predicate = predicate.Or (p => p.Description.Contains (keyword));

  return dataContext.Products.Where (predicate);
}

暫無
暫無

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

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