linq dbContext.SaveChanges()未按.NET中的预期更新单行

j0pj023g  于 12个月前  发布在  .NET
关注(0)|答案(2)|浏览(153)

我有两张table:MySQL中的TableATableB,我试图在. NET中对其执行一些CRUD操作。我编写了一个函数,在TableA中插入新行,然后更新TableB中的单行。传入的请求由incommingID参数组成。insert命令按预期工作,但TableB上的update命令不执行任何操作。它不甚至给予任何误差。方法如下:

public int SomeMethod(int incommingID)
{
    MyDBContext db = new MyDBContext();
    TableAModel rowA = new TableAModel
    {
        // ...data to be inserted
    }
    db.TableA.Add(rowA);

    var query = from tableData in db.TableB
                where tableData.id == incommingID
                select tableData;
    var rowToBeUpdated = query.SingleOrDefault();

    if(rowToBeUpdated != null)
    {
        // isAccepted is false for all rows and is to be set true for this particular id but 
        // when updated, the changes don't reflect and the row still has isAccepted as false.
        rowToBeUpdated.isAccepted = true;
        db.SaveChanges();
    }
    return incommindID;
}

字符串
我甚至尝试用try. catch来 Package 代码,但它没有抛出任何错误。为什么TableA插入可以正常工作,而TableB更新却不能工作?

2admgd59

2admgd591#

我认为你需要问enityframework更新的变化也。

db.TableA.Add(rowA);

字符串
你也需要让EntityFramework来更新这些变化。

db.Entry(rowToBeUpdated).State = EntityState.Modified;

6qftjkof

6qftjkof2#

据我所知,当你在mysql中创建一个表,并将数据类型设置为boolean时,它会传输到TINYINT。尝试将其设置为1。

public int SomeMethod(int incommingID)
{
   // ...PreviousCode

   if(rowToBeUpdated != null)
   {
      // ... due to wrong mapping of the datatype on the column of TableB this line of code is does not work

      rowToBeUpdated.isAccepted = true;     

      // ... this line is enables you to update the data using the sql script is not perfect answer, but it will work and solve the problem else you need to Make a new migration and Scaffolding the whole thing again

      db.Database.ExecuteSqlCommand("UPDATE `DB Name in thserver`.`TabelB` SET `isAccepted` = 1 WHERE `id` = " + incommingID.ToString() + ";");

      db.SaveChanges();
   }
   return incommingID;
}

字符串

相关问题