-5

I need to update EF record, in method I have EF object and another new objct which I want to use to update data from. But I m not sure how to copy data from new object to existing one.

Help please. Here is my code:

public int   PostHomeLead(string _lead)
   {

       try
       {
           int result = 0;
           Lead lead = new Lead();
           lead = new JavaScriptSerializer().Deserialize<Lead>(_lead);

           //check if lead exist with same session id, if so update it other wise add new.
           Lead existingLead = new Lead();
           existingLead = db2.HomeLoanCustRepo.GetByID(lead.Lead_id);

           if (existingLead == null)
           {
               db2.HomeLoanCustRepo.Insert(lead);
               db2.Save();
               result = 1;
           }
           else
           {                   
               db2.HomeLoanCustRepo.Update(lead);
               db2.Save();
               result = 1;
           }
           return result;           
       }
       catch(Exception ex)
       {
           throw ex;
       }

   }
user576510
  • 5,777
  • 20
  • 81
  • 144

1 Answers1

1

Either map the properties manually:

existingLead.Foo = deserializedLead.Foo;
existingLead.Bar = deserializedLead.Bar;
existingLead.Baz = deserializedLead.Baz;

Or use a library that does this, like AutoMapper.

As for your comment, creating a deep copy is what you seem to be after. Note this allows for overposting or mass assignment when you don't verify which properties may be updated. You'll need to Attach() the cloned object when using cloning or mapping, as it will not be the same object as returned by GetByID(), so Entity Framework's change tracker won't recognize it.

Community
  • 1
  • 1
CodeCaster
  • 147,647
  • 23
  • 218
  • 272
  • is it possible using linq or lambda or any out of box class/ library of .net ? – user576510 Nov 12 '14 at 22:12
  • thanks, I m using Attach() but it throw error something primary key is aleady used by another object. Kindly help me what would be solution. – user576510 Nov 12 '14 at 22:24
  • The solution would be searching the web and this site for the actual error you receive and applying what you've learned from what you've read there. I'm sorry, but I don't do [chameleon questions](http://meta.stackexchange.com/questions/43478/exit-strategies-for-chameleon-questions). A last hint: your error is caused by first calling `GetByID()`, which pulls that entity into the change tracker, and using the same context trying to save _another_ entity with the same ID. You need to make that `GetByID()` query `.AsNoTracking()`. – CodeCaster Nov 12 '14 at 22:26