简体   繁体   English

用于更新对象的通用方法中的错误(实体框架4)

[英]Error in generic method for updating object (entity framework 4)

I am developing an application using the EF4 and created a generic method, but generating this error. 我正在使用EF4开发应用程序并创建了通用方法,但是会产生此错误。

Method: 方法:

public Boolean change (T)
{
    ctx.ApplyCurrentValues ​​<T> (t.GetType (). Name, t);
    return save ();
}

And the error that is gerendo is this: 而gerendo的错误是这样的:

An object with a key that matches the key of the supplied object could not be found in the ObjectStateManager. 在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? 有谁知道如何解决这个问题?

ApplyCurrentValues updates values from provided detached entity to attached entity. ApplyCurrentValues值从提供的分离实体更新为连接实体。 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: 您可以将方法修改为:

public Boolean Change<TEntity>(TEntity entity)  where TEntity : EntityObject
{
    // Loads object from DB only if not loaded yet
    ctx.GetObjectByKey(entity.EntityKey);  
    ctx.ApplyCurrentValues​​<T>(entity.GetType().Name, entity);
    ctx.SaveChanges();
}

I am not sure how you even got this to compile, since you used parentheses (T) insted of angle brackets <T> and omitted the parameter t . 我不确定您是怎么编译的,因为您使用了尖括号<T>插入的括号(T)并省略了参数t That is: 那是:

public Boolean change<T>(T t) 
{     
  ctx.ApplyCurrentValues <T> (t.GetType (). Name, t);     
  return save (); 
}

Assuming you meant to type something like this: 假设您要键入以下内容:

public Boolean change<T> (T t)  where T : EntityObject
{
   ctx.ApplyCurrentValues​​<T>(t.GetType().Name, t);
   return save();
}

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. SO上有一些示例,说明如何使用存根或通过从数据库请求具有相同ID的实体来执行此操作,但我还没有看到通用版本。

EntityFramework .net 4 Update entity with a simple method EntityFramework .net 4使用简单方法更新实体

Entity Framework 4 - Where to put "ApplyCurrentValues" Logic? 实体框架4-在哪里放置“ ApplyCurrentValues”逻辑?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM