【问题标题】:MySql Update Query not working with EF6 in ASP.NETMySql 更新查询不适用于 ASP.NET 中的 EF6
【发布时间】:2015-04-24 18:13:08
【问题描述】:
public void PostPlayerAttendance(int id, string attendance)
        {
            using (var ctx = new ApplicationDbContext())
            {
                var upd = ctx.Database.ExecuteSqlCommand(
                    @"UPDATE dbName.Player SET Attendance = @Attendance WHERE Id = @Id",
                    new SqlParameter("Attendance", attendance),
                    new SqlParameter("Id", id));
            }
        }

也试过这个:

@"UPDATE `dbName.Player` SET `Attendance` = @Attendance WHERE `Id` = @Id"

还有这个:

@"UPDATE 'dbName.Player' SET 'Attendance' = @Attendance WHERE 'Id' = @Id"

收到此错误:

发生“MySql.Data.MySqlClient.MySqlException”类型的异常 在 EntityFramework.dll 中,但未在用户代码中处理

附加信息:只能存储 MySqlParameter 对象

【问题讨论】:

  • 在您的代码中尝试使用 MySqlParameter 而不是 SqlParameter。
  • @zed:我一写问题就发现了。无论如何,感谢您快速正确的回答。

标签: mysql sql asp.net sql-update entity-framework-6


【解决方案1】:

您将 SQL 语句和 LINQ 混合在一起。我建议您使用 LINQ,因为您正在使用实体框架。

你的代码应该是这样的:

public void PostPlayerAttendance(int id, string attendance)
        {
            using (var ctx = new ApplicationDbContext())
            {
                var query = (from player in ctx.Players
                             where player.ID == id
                             select player).Single();
                query.Attendance = attendance;
                ctx.SubmitChanges();    
            }
        }

了解 LINQ here

【讨论】:

  • 我成功了。我知道 LINQ,但我故意使用原始 SQL。我想掌握经典,然后继续。
  • @Tomo 如果你想掌握经典,那么可能应该坚持纯 ADO.NET 而不是使用 EF。
  • @mason:我没说我要掌握所有的经典。总比没有好。
【解决方案2】:

知道了。 MySqlParameter 代替 SqlParameter 并且没有 .dbName

var upd = ctx.Database.ExecuteSqlCommand(                        
                    @"UPDATE `Player` SET `Attendance` = @Attendance WHERE `Id` = @Id",
                    new MySqlParameter("Attendance", attendance),
                    new MySqlParameter("Id", id));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-02
    • 2015-09-28
    相关资源
    最近更新 更多