c# - 为什么表达式在 linq 中不起作用

标签 c# linq entity-framework lambda

在EF上工作,需要写一个自定义的where

public virtual IEnumerable GetDataByID<TEntity>() where TEntity : class
{
    if (this.Context == null)
        Initialize<TEntity>();
    TContext context = this.Context;

    var result = context.CreateObjectSet<TEntity>().Where(GetExpression<TEntity>(5));
    return result;
}

public Expression GetExpression<TEntity>(int id) where TEntity : class
{
    ParameterExpression e = Expression.Parameter(typeof(TEntity), "e");
    PropertyInfo propInfo = typeof(TEntity).GetProperty(EntityInfo<TEntity>.GetPkFieldName(this.Context));//(KeyPropertyName);
    MemberExpression m = Expression.MakeMemberAccess(e, propInfo);
    ConstantExpression c = Expression.Constant(id, typeof(int));
    BinaryExpression b = Expression.Equal(m, c);
    Expression<Func<TEntity, bool>> lambda = Expression.Lambda<Func<TEntity, bool>>(b, e);
    return lambda;
}

错误:

The best overloaded method match for 'System.Data.Objects.ObjectQuery.Where(string, params System.Data.Objects.ObjectParameter[])' has some invalid arguments

为什么我的上述语法不起作用,如何修复它?

最佳答案

问题是,CreateObjectSet<TEntity>的结果返回 ObjectSet<TEntity>它定义了自己的 Where 编译器将尝试使用的方法。您提供的参数对此方法无效,因此会出现错误。

您想要使用的是 Linq 的 Queryable.Where 扩展方法如下:

var predicate = GetExpression<TEntity>(5);
var objectSet = context.CreateObjectSet<TEntity>();
var results = System.Linq.Queryable.Where(objectSet, predicate);

关于c# - 为什么表达式在 linq 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14020901/

相关文章:

c# - StringLengthAttribute 是如何工作的?

c# - "System.IO.FileNotFoundException: Could not load assembly ' Xamarin.Android.Support.v13 '"替换为支持库 v4 后

c# - 延迟加载是否在迭代时加载整个集合?

mysql - 从 MySql DB 请求日期字段并保存在 Windows Store APP 类字段中

c# - 如何根据配置切换 EF Core 使用的数据库提供程序?

entity-framework - 确保 DateTime 属性返回 DateTimeKind.Utc

c# - WP7 子弹出窗口中的后退按键处理

c# - 如何使用数据库优先方法读取 asp.net core 中的表

linq - 何时在 LINQ 中使用 lambda 表达式而不是 Where 子句

c# - 按多列返回 linq 组的类型