LINQ实体不会生成有效的MySQL

时间:2015-02-11 11:17:49

标签: c# mysql entity-framework debugging linq-to-entities

您好,我在处理数据库时遇到使用Linq的问题

var acks = (from a in db.eventsandacks
                    where a.triggerDate.Month == 1 && a.joinedrcat > 5 
                    && a.customerName == "CUSTOMER"
                    group a by new { a.triggerDate.Day } into b
                    orderby b.Key.Day
                    select new
                    {
                        Day = b.Key.Day,
                        Count = b.Count()
                    });

有趣的是,如果我只读出Day或Count而不是同时读取两者,那么它是有效的。当我同时运行时我得到了这个错误。

MySql.Data.MySqlClient.MySqlException (0x80004005): Unknown column 'GroupBy1.K1' in 'field list'
  at MySql.Data.MySqlClient.MySqlStream.ReadPacket()
  at MySql.Data.MySqlClient.NativeDriver.GetResult(Int32& affectedRow, Int64& insertedId)
  at MySql.Data.MySqlClient.Driver.GetResult(Int32 statementId, Int32& affected Rows, Int64& insertedId)
  at MySql.Data.MySqlClient.Driver.NextResult(Int32 statementId, Boolean force)

  at MySql.Data.MySqlClient.MySqlDataReader.NextResult()
  at MySql.Data.MySqlClient.MySqlCommand.ExecuteReader(CommandBehavior behavior)
  at MySql.Data.Entity.EFMySqlCommand.ExecuteDbDataReader(CommandBehavior behavior)
  at System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior)
  at System.Data.EntityClient.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand entityCommand, CommandBehavior behavior)

生成的SQL看起来像这样。

{SELECT
`Project1`.`C3` AS `C1`, 
`Project1`.`C2`, 
`Project1`.`C1` AS `C3`
FROM (SELECT
`GroupBy1`.`A1` AS `C1`, 
`GroupBy1`.`K1` AS `C2`, 
1 AS `C3`
FROM (SELECT
COUNT(1) AS `A1`
FROM `eventsandack` AS `Extent1`
 WHERE ((1 = (MONTH(`Extent1`.`triggerDate`))) AND     (`Extent1`.`joinedrcat` > 5)) AND ('CUSTOMER' = `Extent1`.`customerName`)
 GROUP BY 
DAY(`Extent1`.`triggerDate`)) AS `GroupBy1`) AS `Project1`
 ORDER BY 
`Project1`.`C2` ASC}

当我直接在MySQL中运行查询时,我收到此错误

ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that                                                                                                                                                              ht syntax to use near '{SELECT
`Project1`.`C3` AS `C1`,
`Project1`.`C2`,
`Project1`.`C1` AS `C3`
FROM' at line 1

所以我想知道是否有人知道这个问题以及如何解决这个问题。 MySQL服务器在版本(5.1.41)上运行

1 个答案:

答案 0 :(得分:2)

您的问题肯定是由bug引起的,该6.9.6仍然存在于最新版本(changelog,根据我的评论)MySql.Data.Entity版本中。

不幸的是,由于这个错误,LINQ中的大多数group by子句不能与MySql一起使用。

在最新版本中,该错误似乎在SQL语句中创建了虚构的列,并且这些列在模式中根本不存在。

目前有两个可行痛苦的解决方案:1)切换到NHibernate,它具有良好的LINQ-to-HQL支持,或者2)使用.AsEnumerable实现查询或.ToList

更新:2015年7月14日版本6.9.7发布。根据{{​​3}},问题可能尚未解决