【问题标题】:Func<T> in Lambda expression with LinQ to entitiesLambda 表达式中的 Func<T> 与 LinQ 到实体
【发布时间】:2015-11-02 11:08:22
【问题描述】:

我对这段 sn-p 代码有疑问。我使用 LinQ 来实体化

Dictionary<string, int> dictionary = new Dictionary<string, int>();
using (var db = new DiagEntities())
{
    PropertyInfo[] properties = typeof(DiagTab).GetProperties();

    foreach (PropertyInfo property in properties)
    {

        string name = property.Name;
        if (name == "ID_Diag") { continue; } // no column 1 and 2 
        if (name == "Reponse") { continue; } 

        Func<DiagTab, byte> accessor = (Func<DiagTab, byte>)property
                                            .GetMethod
                                            .CreateDelegate(typeof(Func<DiagTab, byte>));

        int sum = db.DiagTabs.Sum(p => accessor(p));  // invoke error

        dictionary.Add(name, sum);                      
    }
    bouba.DataSource = dictionary;
    bouba.DataBind();

编译我有这个错误出现在这一行,我不明白为什么:

int sum = db.DiagTabs.Sum(p => accessor(p))

LINQ to Entities 不支持节点类型“Invoke”LINQ 表达式

你能帮我解决这个问题吗?我应该使用 LINQkit 还是其他?

【问题讨论】:

  • 你确定这是编译错误吗?
  • 对不起,我在 VS 2015 上。当我运行我的网页测试软件时挂起并指定我这个错误并突出显示代码行。我看不到我的网页。

标签: c# entity-framework linq lambda


【解决方案1】:

您的代码存在 2 个主要问题。

首先,EnumerableQueryable 都没有用于 Sumbyte 方法,因此最接近的是与 int 一起使用的方法。

其次,更重要的是,LINQ to Entities 主要与Queryable 一起使用,而Expression&lt;Func&lt;...&gt;&gt; 又使用Expression&lt;Func&lt;...&gt;&gt;(与仅使用Func&lt;...&gt;Enumerable 形成对比)。您的代码试图通过从 func 创建一个表达式来组合它们,但正如错误消息所述,这是不受支持的。

解决方案是使用 System.Linq.Expressions 命名空间中的类/方法构建表达式 - Expression.Parameter 用于创建参数,Expression.Property 用于属性访问器,Expression.Convert 用于更改类型,@ 987654324@把它们放在一起,像这样

foreach (var property in typeof(DiagTab).GetProperties())
{    
    string name = property.Name;
    if (name == "ID_Diag") { continue; } // no column 1 and 2 
    if (name == "Reponse") { continue; } 

    // selector = (DiagTab source) => (int)source.Property
    var source = Expression.Parameter(typeof(DiagTab), "source");
    var selector = Expression.Lambda<Func<DiagTab, int>>(
        Expression.Convert(Expression.Property(source, property), typeof(int)),
        source);

   int sum = db.DiagTabs.Sum(selector);
   dictionary.Add(name, sum);                      
}

【讨论】:

  • 谢谢谢谢伊万。太完美了!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-08-22
  • 2021-06-19
  • 1970-01-01
  • 2015-09-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多