1

I've got a Method that has a Model "Address" as a parameter.

Now inside this method I want to "overwrite" my existing Address in the Database with the provided address - just like updating it in SQL.

I do the inserting-bit like this:

            Context.Addresses.AddObject(adr);
            Context.SaveChanges();

How do I do the updating-part?

I've tried something like this:

   public void Update(Address adr)
   {
            Context.Addresses.Attach(adr);
            Context.SaveChanges();
   }

Sadly, this does not work... I've also tried plenty of other codes, but none of them worked.

So how can I update an existing record in my DB when I get an object of the modified record as a parameter?

Thank you

4
  • Easiest would be to retrieve the existing address, then use ModelCopier or AutoMapper to update it with the new values, then call SaveChanges(). Commented Jan 26, 2012 at 22:54
  • What's ModelCopier or AutoMapper? Commented Jan 26, 2012 at 23:08
  • See AutoMapper and a note about ModelCopier Commented Jan 27, 2012 at 6:05
  • possible duplicate of how to update an entity in Entity Framework 4 .NET Commented Jan 27, 2012 at 9:14

1 Answer 1

2

You need to tell EF that the entity is updated by calling ApplyCurrentValues

 public void Update(Address adr)
 {
        Context.Addresses.ApplyCurrentValues(adr);

        Context.SaveChanges();
 }
Sign up to request clarification or add additional context in comments.

4 Comments

This does not work. I can't remember the exact exception, but it says something like "ObjectManager can't manage more than one object with the same KeyField" or something like that.
@SeToY Then use ApplyCurrentValues method as shown in updated answer
This results in: "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." When I first call context.Attach(adr), no exception occurs but it doesn't update the row in the db
@SeToY Check whether an istance with same PK is tracked by the context. If so use ApplyCurrentValues. Otherwise Attach the new instance and set its state as Modified.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.