MySql Update Query无法在ASP.NET中使用EF6

时间:2015-04-24 18:13:08

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

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对象

2 个答案:

答案 0 :(得分:0)

您正在混合SQL语句和LINQ togheter。我建议您使用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

答案 1 :(得分:0)

Got it. MySqlParameter instead of SqlParameter and without .dbName.

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