An object with a key that matches the key of the supplied object could not be found in the ObjectStateManager

…衆ロ難τιáo~ 提交于 2019-12-14 03:19:01

问题


I want to update record from FormView with ObjectDataSource and lose my day to solve this error.

An object with a key that matches the key of the supplied object could not be found in the ObjectStateManager. Verify that the key values of the supplied object match the key values of the object to which changes must be applied.

My code is below

private static Entities1 _db = null;

public static Entities1 CreateDataContext()
{
    if (_db == null)
    {
        _db = new Entities1(System.Configuration.ConfigurationManager.ConnectionStrings["Entities1"].ConnectionString);
        _db.games.MergeOption = MergeOption.NoTracking;
        _db.my_aspnet_users.MergeOption = MergeOption.NoTracking;
        _db.platforms.MergeOption = MergeOption.NoTracking;
    }
    return _db;
}

public void Update(game item)
{
    Entities1 DB = CreateDataContext();
    item.modified = DateTime.Now;
    var obj = (from u in DB.games
               where u.idgames == item.idgames
               select u).First();
    DB.games.ApplyCurrentValues(item);//Error Here
    DB.SaveChanges();         
}

回答1:


In your method:

public void Update(game item)
{
    Entities1 DB = CreateDataContext();
    item.modified = DateTime.Now;
    var obj = (from u in DB.games
               where u.idgames == item.idgames
               select u).First();
    DB.games.ApplyCurrentValues(item);//Error Here
    DB.SaveChanges();         
}

item is not attached so it can't be updated. That's pretty much what the error message is telling you, too.

It looks like you'd want to use obj which is retrieved from your context. Then set the values of obj to those in item, and use obj to make the updates.

EDIT for sample...

If you just want to set the modified date and time you'd do this:

public void Update(game item) {
    Entities1 DB = CreateDataContext();

    var obj = (from u in DB.games
               where u.idgames == item.idgames
               select u).SingleOrDefault();
    if (obj == null) {
      // handle the case where obj isn't found
      // probably by throwing an exception
    }

    obj.modified = DateTime.Now;
    DB.games.ApplyCurrentValues(obj);
    DB.SaveChanges(); 
}


来源:https://stackoverflow.com/questions/8521794/an-object-with-a-key-that-matches-the-key-of-the-supplied-object-could-not-be-fo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!