更新对象的通用方法出错(实体框架 4)
我正在使用 EF4 开发一个应用程序并创建了一个通用方法,但生成了此错误。
方法:
public Boolean change (T)
{
ctx.ApplyCurrentValues <T> (t.GetType (). Name, t);
return save ();
}
gerendo 的错误是这样的:
在 ObjectStateManager 中找不到其键与所提供对象的键匹配的对象。验证提供的对象的键值是否与必须应用更改的对象的键值匹配。
有人知道如何解决这个问题吗?
I am developing an application using the EF4 and created a generic method, but generating this error.
Method:
public Boolean change (T)
{
ctx.ApplyCurrentValues <T> (t.GetType (). Name, t);
return save ();
}
And the error that is gerendo is this:
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.
Does anyone know how to solve this problem?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
ApplyCurrentValues
将值从提供的分离实体更新为附加实体。此异常表示您没有具有相同密钥的附加实体。这意味着在调用此方法之前,您没有在同一上下文中从数据库加载实体。您可以将您的方法修改为:
ApplyCurrentValues
updates values from provided detached entity to attached entity. This exception says that you don't have attached entity with the same key. It means you didn't load entity from database on the same context before you called this method.You can modify your method to:
我不确定你是如何编译它的,因为你使用了括号
(T)
代替尖括号
并省略了参数t< /代码>。那是:
I am not sure how you even got this to compile, since you used parentheses
(T)
insted of angle brackets<T>
and omitted the parametert
. That is:假设您打算输入如下内容:
由于对象上下文尚未加载您要更新的实体,因此失败,您必须首先从数据库中提取实体。
关于如何使用存根或通过从数据库请求具有相同 id 的实体来执行此操作,有一些示例,但我还没有看到通用版本。
EntityFramework .net 4 使用简单方法更新实体
实体框架 4 - 在哪里放置“ApplyCurrentValues”逻辑?
Assuming you meant to type something like this:
This fails because the object context hasn't loaded the entity that you want to update, you will have to pull the entity from the DB first.
There are some examples around on SO on how to do this either with a stub or by requesting the entity with the same id from the DB, but I haven't seen a generic version yet.
EntityFramework .net 4 Update entity with a simple method
Entity Framework 4 - Where to put "ApplyCurrentValues" Logic?