簡體   English   中英

LINQ to Entities定制方法

[英]LINQ to Entities custom method

在我的代碼中,我有:

context.TableA
            .Where(x =>
                x.Created >= startDate
                && context.TableB.RecordExists(x.Id, 1));

而RecordExists的定義如下:

public static bool RecordExists(this IQueryable<TableB> entity, int entityId, int entityTypeId)
{
    return entity.Any(x => x.EntityId == entityId && x.EntityTypeId == entityTypeId);
}

上面的調用失敗了

NotSupportedException:LINQ to Entities無法識別方法“ Boolean RecordExists(System.Linq.IQueryable`1 [TableB],Int32,Int32)”方法,並且該方法無法轉換為商店表達式。

但是如果我將查詢更改為:

 context.TableA
            .Where(x =>
                x.Created >= startDate
                && context.TableB.Any(p => p.EntityId == x.Id && p.EntityTypeId == 1));

它工作得很好,是否可以在查詢中使用此方法?

嘗試使用表達式

表達式定義

public Expression<Func<TableA, bool>> RecordExists(IEnumerable<TableB> entities, int entityTypeId)
{
    return a => entities.Any(b => b.Id == a.EntityId && b.EntityTypeId == entityTypeId);
}

return context.TableA
    .Where(x => x.Created >= startDate)
    .Where(RecordExists(context.TableB, 1));

實體框架過濾器

Linq to SQL使用“表達式樹”將lambda表達式轉換為sql表達式。 因此,您不能使用方法,只能使用內聯表達式。 但是您可以在Linq中使用方法來進行收集。 如果首先在TableA上調用.ToList()函數,則可以調用方法。 但是.ToList()函數將首先檢索內存中的所有內容,然后對其進行過濾。 因此,強烈不建議這樣做。

暫無
暫無

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

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