我有一个在SQL Server中完美运行的SQL查询。
SELECT sum(CONVERT(float,[amount]))
FROM [transaction]
where [response_code] = '100' and merchant_id = '14
将其转换为linq时,这是我的结果查询和我收到的异常。我究竟做错了什么?
LINQ =
float count = dbContext.transactions.Where(trx => trx.response_code.Equals("100"))
.Where(trx=>trx.merchant_id.Equals(mid))
.Sum(i => float.Parse(i.amount));
错误=
{System.InvalidOperationException: Could not translate expression 'Table(transaction).Where(trx => trx.response_code.Equals("100")).Where(trx => trx.merchant_id.Equals(Convert(Invoke(value(System.Func`1[System.Nullable`1[System.Int32]]))))).Sum(i => Parse(i.amount))' into SQL and could not treat it as a local expression.
at System.Data.Linq.SqlClient.ObjectReaderCompiler.Generator.Generate(SqlNode node, LocalBuilder locInstance)
at System.Data.Linq.SqlClient.ObjectReaderCompiler.Generator.GenerateBody(ILGenerator generator, SqlExpression expression)
at System.Data.Linq.SqlClient.ObjectReaderCompiler.CompileDynamicMethod(Generator gen, SqlExpression expression, Type elementType)
at System.Data.Linq.SqlClient.ObjectReaderCompiler.Compile(SqlExpression expression, Type elementType)
at System.Data.Linq.SqlClient.SqlProvider.GetReaderFactory(SqlNode node, Type elemType)
at System.Data.Linq.SqlClient.SqlProvider.System.Data.Linq.Provider.IProvider.Execute(Expression query)
at System.Data.Linq.DataQuery`1.System.Linq.IQueryProvider.Execute[S](Expression expression)
at System.Linq.Queryable.Sum[TSource](IQueryable`1 source, Expression`1 selector)
at WCF_SOAP_REST_Service.Service.totalAcceptedTransactionCount(Nullable`1 mid) in c:\Users\Monet\Documents\Visual Studio 2012\Projects\WCF_SOAP_REST_Service\Service.svc.cs:line 845}
答案 0 :(得分:1)
问题是Linq To Entities无法识别float.Parse()方法,也无法将其转换为有效的商店语句。
你必须先用方法Select(),AsEnumerable(),ToList()......枚举Where结果。
在这里,您可以使用Linq to Entities转换为有效Sql语句的方法:
CLR Method to Canonical Function Mapping
这应该有效:
dbContext.transactions.Where(trx => trx.response_code.Equals("100"))
.Where(trx=>trx.merchant_id.Equals(mid))
.ToList() // Or AsEnumerable(), or Select()...
.Sum(i => float.Parse(i.amount));