user948365
user948365

Reputation:

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

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();         
}

Upvotes: 0

Views: 5979

Answers (1)

Yuck
Yuck

Reputation: 50835

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(); 
}

Upvotes: 6

Related Questions