2

I have an entity that has so many properties that I don't want to have to manually do something like

public void Update(Contact cont)
    {
        using (var ctx = new DatabaseEntities())
        {
            var res = from n in ctx.Contacts
                          where n.ContactID == cont.ContactID
                          select n;

            var selContact = res.First();
            selContact.AddressSuiteNumber = cont.AddressSuiteNumber;
            selContact.PhoneNumber = cont.PhoneNumber;
            /* and doing this for eeeeeeevery 40 properties */
            ctx.SaveChanges();

        }

    }

I tried

selContact = cont

To no avail. Is there any such quick way to copy data from the instance of the entity passed as argument in the Update() method to the one found in the LINQ select and then save it?

klashar
  • 2,519
  • 2
  • 28
  • 38
Francis Ducharme
  • 4,848
  • 6
  • 43
  • 81
  • I found [this](http://stackoverflow.com/questions/930433/apply-properties-values-from-one-object-to-another-of-the-same-type-automaticall) Anyone has any other ideas ? – Francis Ducharme Aug 02 '12 at 14:27

1 Answers1

3

If your entity is not yet attached to the context, you could try attaching it and change its state to Modified:

using (var ctx = new DatabaseEntities())
{
    ctx.Contacts.Attach(cont);

    // Marks all properties as modified, so new values will be pushed to DB on SaveChanges
    ctx.ObjectStateManager.ChangeObjectState(cont, System.Data.EntityState.Modified);

    ctx.SaveChanges();
}
ken2k
  • 48,145
  • 10
  • 116
  • 176