本文介绍了在ObjectStateManager中找不到具有与提供对象的键匹配的键的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想从 FormView
中更新 ObjectDataSource
的记录,并且失去了解决此错误的一天。
I want to update record from FormView
with ObjectDataSource
and lose my day to solve this error.
我的代码在
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();
}
推荐答案
在您的方法中:
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.
看起来你想使用 obj
从您的上下文检索。然后将 obj
的值设置为项目
中的值,然后使用 obj
进行更新。
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.
编辑样本 ...
如果您只想设置修改的日期和时间,您可以执行此操作:
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();
}
这篇关于在ObjectStateManager中找不到具有与提供对象的键匹配的键的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!