简体   繁体   中英

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.

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?

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:

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 . 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.

EntityFramework .net 4 Update entity with a simple method

Entity Framework 4 - Where to put "ApplyCurrentValues" Logic?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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