我有一个问题,我现在无法回答。问题出现在真实场景中,但我简化了问题。我只是想在LINQ中选择Select。也许它应该以另一种方式完成?
以下代码按预期工作:
var test = Math.Round(99.00000000000000000000000000m, 3); // 99.000m
var testLinq1 = new System.Collections.Generic.List<string>() { "dummy" }
.Select(r => new
{
value = Math.Round(99.00000000000000000000000000m, 3) // 99.000m
})
.ToList();
但这两行都引发了异常:
var testLinq2 = _dbContext.SomeEntity
.Select(r => new
{
value = Math.Round(99.00000000000000000000000000m) // Throws an exception.
})
.ToList();
var testLinq3 = _dbContext.SomeEntity
.Select(r => new
{
value = Math.Round(99.00000000000000000000000000m, 3) // Throws an exception.
})
.ToList();
例外是:
类型&#39; System.InvalidCastException&#39;的例外情况发生在Microsoft.EntityFrameworkCore.dll中但未在用户代码中处理
其他信息:无法投射“System.Int64&#39;”类型的对象。输入&#39; System.Decimal&#39;。
InnerException:null
来源:MySqlConnector
StackTrace是:
at MySql.Data.MySqlClient.MySqlDataReader.GetDecimal(Int32 ordinal)
at lambda_method(Closure , DbDataReader )
at Microsoft.EntityFrameworkCore.Storage.Internal.TypedRelationalValueBufferFactory.Create(DbDataReader dataReader)
at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable.Enumerator.BufferlessMoveNext(Boolean buffer)
at Microsoft.EntityFrameworkCore.Query.QueryMethodProvider.<_ShapedQuery>d__3`1.MoveNext()
at Microsoft.EntityFrameworkCore.Query.Internal.MySqlQueryingEnumerable`1.MySqlEnumerator.MoveNext()
at System.Linq.Enumerable.SelectEnumerableIterator`2.MoveNext()
at Microsoft.EntityFrameworkCore.Query.Internal.LinqOperatorProvider.ExceptionInterceptor`1.EnumeratorExceptionInterceptor.MoveNext()
at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
at ProjectName.Controllers.SomeController.SomeAction(Int32 propertyId) in D:\Work\Project\ProjectName\Controllers\SomeController.cs:line 419
at lambda_method(Closure , Object , Object[] )
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.<InvokeActionFilterAsync>d__28.MoveNext()
它&#39; S
"Microsoft.NETCore.App": {
"version": "1.0.1",
"type": "platform"
}
我正在使用
"Microsoft.EntityFrameworkCore": "1.1.1",
"Pomelo.EntityFrameworkCore.MySql": "1.1.1"
感谢Tim Schmelter现在显而易见的是,在第一种情况下它是Linq-to-Objects,而在第二种情况下它是Linq-to-Entities和Math.Round翻译成SQL。鉴于问题的提法,这甚至可以被认为是一个答案。但我很好奇,纯粹假设,如果我想使用MySQL服务器舍入功能怎么办?正如James Curran所说,为什么这段代码可以正常使用SQL Server Compact DB,但是它不适用于MySQL?它看起来像是连接器的错误。