无法在日期时间文字上将类型为“ System.String”的对象转换为类型为“ System.DateTime”的对象

时间:2019-09-26 05:38:49

标签: mysql entity-framework asp.net-core .net-core

我们有一个游戏主机的MySQL数据库,该数据库可以运行一组特定游戏类型的游戏。我有一个linq语句,该语句返回主机ID,名称和标题+主机上上次游戏的开始时间(如果有)。

context.HostConfigurations.Select (h => new HostStatus {
                id = h.IdHostConfigurations,
                hostname = h.Hostname,
                gameTitle = h.IdGamesLast.HasValue ? h.LastGameNavigation.GameTypeNavigation.Title : "-",
                gameStart = h.IdGamesLast.HasValue ? h.LastGameNavigation.Gamestart : DateTimeOffset.MinValue,
                gameStartFriendly = h.IdGamesLast.HasValue ? h.LastGameNavigation.Gamestart.ToString ("ddd HH:mm") : "-"
            }).ToList ();

日志输出如下:

INFO: Microsoft.EntityFrameworkCore.Database.Command Executed DbCommand (21ms) [Parameters=[@__nowMinus24Hrs_0='?' (DbType = DateTimeOffset), @__nowMinusTenMinutes_1='?' (DbType = DateTimeOffset)], CommandType='Text', CommandTimeout='30']
SELECT `h`.`idHostConfigurations` AS `id`, `h`.`hostname`, CASE
    WHEN `h`.`idGamesLast` IS NOT NULL
    THEN `h.LastGameNavigation.GameTypeNavigation`.`title` ELSE '-'
END AS `gameTitle`, CASE
    WHEN `h`.`idGamesLast` IS NOT NULL
    THEN `h.LastGameNavigation`.`gamestart` ELSE '0001-01-01 00:00:00.000000'
END AS `gameStart0`, CASE
WHEN `h`.`idGamesLast` IS NOT NULL
    THEN TRUE ELSE FALSE
END, `h.LastGameNavigation`.`gamestart`
FROM `HostConfigurations` AS `h`
LEFT JOIN `Games` AS `h.LastGameNavigation` ON `h`.`idGamesLast` = `h.LastGameNavigation`.`idGames`
LEFT JOIN `GameTypes` AS `h.LastGameNavigation.GameTypeNavigation` ON `h.LastGameNavigation`.`idGameTypes` = `h.LastGameNavigation.GameTypeNavigation`.`idGameTypes`

ERROR: Microsoft.EntityFrameworkCore.Query An exception occurred while iterating over the results of a query for context type '...'.
System.InvalidCastException: Unable to cast object of type 'System.String' to type 'System.DateTime'.
   at MySqlConnector.Core.Row.GetDateTime(Int32 ordinal) in C:\projects\mysqlconnector\src\MySqlConnector\Core\Row.cs:line 285
   at MySqlConnector.Core.Row.GetDateTimeOffset(Int32 ordinal) in C:\projects\mysqlconnector\src\MySqlConnector\Core\Row.cs:line 288
   at MySql.Data.MySqlClient.MySqlDataReader.GetFieldValue[T](Int32 ordinal) in C:\projects\mysqlconnector\src\MySqlConnector\MySql.Data.MySqlClient\MySqlDataReader.cs:line 261
   at lambda_method(Closure , DbDataReader )
   at Microsoft.EntityFrameworkCore.Storage.Internal.TypedRelationalValueBufferFactory.Create(DbDataReader dataReader)
   at Microsoft.EntityFrameworkCore.Query.Internal.AsyncQueryingEnumerable`1.AsyncEnumerator.BufferlessMoveNext(DbContext _, Boolean buffer, CancellationToken cancellationToken)
   at Pomelo.EntityFrameworkCore.MySql.Storage.Internal.MySqlExecutionStrategy.ExecuteAsync[TState,TResult](TState state, Func`4 operation, Func`4 verifySucceeded, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.Query.Internal.AsyncQueryingEnumerable`1.AsyncEnumerator.MoveNext(CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.Query.Internal.AsyncLinqOperatorProvider.ExceptionInterceptor`1.EnumeratorExceptionInterceptor.MoveNext(CancellationToken cancellationToken)

如果我从lambda方法中注释掉'gameStart = ...'行,则不会发生异常。显然,这是因为MinValue的datetime文字在结果集中被解释为字符串。这似乎是对MySQL连接器的严重限制?

任何解决方法的想法都值得赞赏!

2 个答案:

答案 0 :(得分:1)

有一种解决方法。您可以将最小日期变量声明为DateTimeOffset? min = DateTimeOffset.MinValue,并在查询中使用它。

context.HostConfigurations.Select (h => new HostStatus {
            id = h.IdHostConfigurations,
            hostname = h.Hostname,
            gameTitle = h.IdGamesLast.HasValue ? h.LastGameNavigation.GameTypeNavigation.Title : "-",
            gameStart = h.IdGamesLast.HasValue ? h.LastGameNavigation.Gamestart : min ,
            gameStartFriendly = h.IdGamesLast.HasValue ? h.LastGameNavigation.Gamestart.ToString ("ddd HH:mm") : "-"
        }).ToList ();

答案 1 :(得分:0)

目前,通过强制表达式的本地求值,我找到了解决连接器问题的方法:

        var hosts = await context.HostConfigurations.Include (h => h.LastGameNavigation).ThenInclude (lg => lg.GameTypeNavigation).ToListAsync ();

        var l = new List<HostStatus> ();

        hosts.ForEach (h => {
            l.Add (new HostStatus {
                id = h.IdHostConfigurations,
                hostname = h.Hostname,
                gameTitle = h.IdGamesLast.HasValue ? h.LastGameNavigation.GameTypeNavigation.Title : "-",
                gameStart = h.IdGamesLast.HasValue ? h.LastGameNavigation.Gamestart : DateTimeOffset.MinValue,
                gameStartFriendly = h.IdGamesLast.HasValue ? h.LastGameNavigation.Gamestart.ToString ("ddd HH:mm") : "-",
            });
        });