简体   繁体   中英

How to update record using Entity Framework 6 MySQL

I am looking for the correct way to update a record using Entity Framework 6 MYSQL.

Below is what I'm using right now.

    public void Update(User user)
    {
        using (var ctx = new DataSystemDbContext())
        {
            ctx.Users.Attach(user);
            ctx.Entry(user).State = EntityState.Modified;
            ctx.SaveChanges();
        }
    }

And on my unit test.

    [TestMethod]
    public async Task User_Update()
    {

        var userService = new UserService();
        var user = userService.GetById(1);
        user.FullName = "Test Fullname";
        userService.Update(user);
        var updatedUser = userService.GetById(1);

        Assert.AreEqual(user.FullName, updatedUser.FullName);
    }

When it executes all my user records are updated.

This is also related to my another post. But on my another post it's using a live context, unlike this one.

MySQL Entity Framework 6 Update affecting all rows Code First

I fixed this issue by commenting out or not using the generated procedure for CRUD.

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
     base.OnModelCreating(modelBuilder);    
     // Mapp all entities in a single line.    
     //modelBuilder.Types().Configure(t => t.MapToStoredProcedures());
}

Generated SQL

UPDATE `Users` SET `Email`=@gp1 WHERE `Id` = 6
-- @gp1: 'myemail@gmail.com' (Type = String, IsNullable = false, Size = 17)
-- Executing asynchronously at 25/06/2018 8:30:21 AM +08:00
-- Completed in 2 ms with result: 1

I'm not sure if the MySQL Provider has a bug or not.

  • Entity Framework v6.1.3
  • MySQL.Data.Entity v6.10.7
  • MySQL.Data v6.10.7

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM