实体框架 - SaveChanges未反映在数据库中

时间:2016-07-28 11:39:49

标签: entity-framework

SaveChanges没有反映在数据库中

我有以下代码

public async Task<int> Post([FromBody] UserEntry userEntry)
{
    UserEntry dbUserEntry;

    using (DBContext db = new DBContext())
    {
      // update
      dbUserEntry = this.db.UserEntries
                     .Where(u => u.UserEntryID == userEntry.UserEntryID)
                     .Include(u => u.EntryPlayers.Select(y => y.Player))
                     .FirstOrDefault();

      dbUserEntry.TeamName = userEntry.TeamName;
      dbUserEntry.EntryPlayers = userEntry.EntryPlayers;

      //db.Entry(dbUserEntry).State = EntityState.Modified;
      return db.SaveChanges();
    }

}

我在某处读到了我需要将状态设置为已修改但如果我取消注释该行

// db.Entry(dbUserEntry).State = EntityState.Modified;

我收到错误: -

IEntityChangeTracker的多个实例无法引用实体对象。

关于如何让SaveChanges工作的任何想法?

1 个答案:

答案 0 :(得分:1)

使用Find()方法代替FirstOrDefault()

dbUserEntry = this.db.UserEntries
                 .Include(u => u.EntryPlayers.Select(y => y.Player))
                 .Find(u => u.UserEntryID == userEntry.UserEntryID)