如何在LINQ中使用Math.X函数? [英] How can I use Math.X functions with LINQ?

查看:49
本文介绍了如何在LINQ中使用Math.X函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的表(SQL Server和EF6) Myvalues ,其中的列为 Id & (双精度)

I have a simple table (SQL server and EF6) Myvalues, with columns Id & Value (double)

我正在尝试获取此表中所有值的自然对数之和.我的LINQ语句是:

I'm trying to get the sum of the natural log of all values in this table. My LINQ statement is:

            var sum = db.Myvalues.Select(x => Math.Log(x.Value)).Sum();

它可以编译,但是我得到了RTE:

It compiles fine, but I'm getting a RTE:

LINQ to Entities无法识别方法'Double Log(Double)',并且该方法无法转换为商店表达式.

我在做什么错/我该如何解决?

What am I doing wrong/how can I fix this?

FWIW,我可以直接对数据库执行以下SQL查询,这给了我正确的答案:

FWIW, I can execute the following SQL query directly against the database which gives me the correct answer:

select exp(sum(LogCol)) from
    (select log(Myvalues.Value) as LogCol From Myvalues 
) results

推荐答案

LINQ尝试将Math.Log转换为SQL命令,以便针对数据库执行该命令.

LINQ tries to translate Math.Log into a SQL command so it is executed against the DB.

不支持此操作.

另一种解决方案是使用.ToList()从数据库中检索所有项目,并使用LINQ to Objects(而不是LINQ to Entities)执行Math.Log.

The other solution is to retrieve all your items from your DB using .ToList(), and execute Math.Log with LINQ to Objects (not LINQ to Entities).

这篇关于如何在LINQ中使用Math.X函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆