Med*_*edo 3 .net c# linq entity-framework
在我的代码中,我有:
context.TableA
.Where(x =>
x.Created >= startDate
&& context.TableB.RecordExists(x.Id, 1));
Run Code Online (Sandbox Code Playgroud)
RecordExists 定义如下:
public static bool RecordExists(this IQueryable<TableB> entity, int entityId, int entityTypeId)
{
return entity.Any(x => x.EntityId == entityId && x.EntityTypeId == entityTypeId);
}
Run Code Online (Sandbox Code Playgroud)
上述调用失败
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));
Run Code Online (Sandbox Code Playgroud)
它工作得很好,有没有办法在查询中使用这种方法?
尝试使用表达式
表达式定义
public Expression<Func<TableA, bool>> RecordExists(IEnumerable<TableB> entities, int entityTypeId)
{
return a => entities.Any(b => b.Id == a.EntityId && b.EntityTypeId == entityTypeId);
}
Run Code Online (Sandbox Code Playgroud)
例子
return context.TableA
.Where(x => x.Created >= startDate)
.Where(RecordExists(context.TableB, 1));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2888 次 |
| 最近记录: |