SeToY
SeToY

Reputation: 5895

Entity Framework 4: Update Single Record

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

Upvotes: 1

Views: 5092

Answers (1)

Eranga
Eranga

Reputation: 32447

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

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

        Context.SaveChanges();
 }

Upvotes: 2

Related Questions