簡體   English   中英

EF Core多個“ where”未翻譯

[英]EF Core multiple “where” are not translated

我有一個數據庫模型,我想在運行時對不同的屬性進行過濾。 為此,我有一些方法,每個方法根據屬性運行一個“ where”子句,並返回一個IQueryable。 問題是該子句無法轉換為SQL,因此查詢不使用“ WHERE”語句運行,返回整個表,服務器正在執行過濾,這既緩慢又昂貴。

從日志中,我收到一條消息:

Microsoft.EntityFrameworkCore.Query:警告:LINQ表達式'where(new(新EntityId([ed] .EntityId).Id == __entityId_Id_1))'無法翻譯,將在本地進行評估。

我的問題是:我在這里正確嗎? 如果是的話,我下一步應該去哪里看?

主要功能

public static EntityDataDTO GetEntityByKey(this IQueryable<EntityDTO> query, IEntityId entityId, EntityTypeDTO type, string key)
{
    return query
        .HasEntity(entityId)
        .HasType(type)
        .HasKey(key)
        .FirstOrDefault();
}

public static EntityDataDTO GetEntity(this IQueryable<EntityDTO> query, IEntityId entityId, EntityTypeDTO type)
{
    return query
        .HasEntity(entityId)
        .HasType(type)
        .FirstOrDefault();
}

子函數

public static IQueryable<EntityDDTO> HasType(this IQueryable<EntityDTO> query, EntityTypeDTO type)
{
    return query.Where(ed => ed.Type == type);
}

public static IQueryable<EntityDTO> HasEntity(this IQueryable<EntityDTO> query, IEntityId entityId)
{
    return query.Where(ed => ed.EntityId.Id == entityId.Id);
}

EntityDTO

public class EntityDTO
    {
        public int Id { get; set; }
        public EntityTypeDTO Type { get; set; }
        public string Key { get; set; }
        public string Value { get; set; }
        public IEntityId EntityId { get; set; }
        public IPartnerId PartnerId { get; set; }
    }

我發現您發布的任何代碼都沒有問題。 但是,您忽略了發布HasKey方法的定義,因此我假設問題確實存在。

無論如何,警告都會告訴您確切的問題代碼: new EntityId(ed.EntityId).Id 找到那段代碼並更正它。 諸如調用新類型之類的東西無法轉換為SQL,因此EF必須在內存中運行它。 從技術上講,您可以繼續並僅允許EF執行此操作。 但是,通常這表明您將要運行效率低下的查詢,因此您應該尋找一種更好的方法,而不必在內存中運行該部分查詢。

您可以使用表達式謂詞並為自己建立一個常見的可重用表達式的庫。 這是將其添加到EntityDTO的示例,請注意,它返回一個表達式,而不是實際的IQueryable / IEnumerable:

public partial class EntityDTO
{
  public static Expression<Func<EntityDTO, bool>> HasType(EntityTypeDTO type)
  {
    return ed => ed.Type == type;
  }
  public static Expression<Func<EntityDTO, bool>> HasEntity(IEntityId entityId)
  {
      return ed => ed.EntityId.Id == entityId.Id;
  }
}

暫無
暫無

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

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