gpt4 book ai didi

c# - 如何使用 Linq to Entity Framework 在表达式中使用函数?

转载 作者:太空狗 更新时间:2023-10-29 19:58:23 26 4
gpt4 key购买 nike

我正在尝试编写一个 linq to entity 扩展方法,该方法采用 Func 来选择属性 Id 并将其与 id 列表进行比较。

public class A
{
public int AId { get; set; }
}

public class B
{
public int BId { get; set; }
}

扩展方法

public static IQueryable<T> WithId<T>(this IQueryable<T> entities,
Func<T, int> selector, IList<int> ids)
{
Expression<Func<T, bool>> expression = x => ids.Contains(selector(x));
return entities.Where(expression); // error here (when evaluated)
}

调用方法

var ids = new List<int> { 1, 2, 3 };
DbContext.EntityAs.WithId(e => e.AId, ids);
DbContext.EntityBs.WithId(e => e.BId, ids);

我遇到的问题是它正在尝试调用 Entity Framework 中不允许的函数。

如何使用属性选择器 (Func) 来评估查询?

最佳答案

您必须传递 Expression<Func<T, int>>而不是 Func<T, int>并自己建立完整的表达方式。这将达到目的:

public static IQueryable<T> WithId<T>(this IQueryable<T> entities,
Expression<Func<T, int>> propertySelector, ICollection<int> ids)
{
var property =
(PropertyInfo)((MemberExpression)propertySelector.Body).Member;

ParameterExpression parameter = Expression.Parameter(typeof(T));

var expression = Expression.Lambda<Func<T, bool>>(
Expression.Call(
Expression.Constant(ids),
typeof(ICollection<int>).GetMethod("Contains"),
Expression.Property(parameter, property)),
parameter);

return entities.Where(expression);
}

当您尝试在使用 O/RM 时保持代码 DRY 时,您将经常不得不摆弄表达式树。这是 another fun example .

关于c# - 如何使用 Linq to Entity Framework 在表达式中使用函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19052507/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com