0

My .net web service reads an entity from the DB and sends it to a client application.

The client application modifies some fields in the entity and then submits the entity back to the server to be updated in the DB.

The surefire but laborious way to do this goes something like:

public void Update(MyEntity updatedEntity)
{
    using (var context = new MyDataContext())
    {
        var existingEntity = context .MyEntities.Single(e => e.Id == updatedEntity.Id);
        existingEntity.FirstName = updatedEntity.Name;
        existingEntity.MiddleName = updatedEntity.MiddleName;
        existingEntity.LastName = updatedEntity.LastName;
        // Rinse, repeat for all members of MyEntity...
        context.SubmitChanges();
    }
}

I don't want to go down this path because it forces me to specify each and every member property in MyEntity. This is will likely break in case MyEntity's structure is changed.

How can I take the incoming updatedEntity and introduce it to LINQ to SQL whole for update?

I've tried achieving this with the DataContext's Attach() method and entered a world of pain.

Is Attach() the right way to do it? Can someone point to a working example of how to this?

urig
  • 16,016
  • 26
  • 115
  • 184
  • 3
    `Attach()` is one of the ways to do it. But i usually create Mapper for this situations. [Automapper](http://automapper.org/) do the most simple cases from the box. – teo van kot Oct 30 '15 at 10:36
  • 1
    If you have problems with `Attach` what are they? – Panagiotis Kanavos Oct 30 '15 at 10:44
  • My current issue with `Attach()` is that if the client sets the entity's rowversion property to null then context.SubmitChanges() throws an exception saying "Row not found or changed". – urig Oct 30 '15 at 10:50
  • Looks like a misuse of EF. Using EF in a CRUD style often throws away a lot of value. – usr Dec 24 '15 at 11:08

1 Answers1

1

Attach is indeed one way to do it.

That said...

The surefire but laborious way to do this goes something like

The right way if you ask me.

This is will likely break in case MyEntity's structure is changed

I personally would expect to modify my Update business method in case the database schema has changed:

  • if it's an internal change that doesn't change the business, then there is just no reason to modify the code that calls your business method. Let your business method be in charge of the internal stuff
  • if it's some change that require you to modify your consumers, then so be it, it was required to update the calling code anyway (at least to populate for instance the new properties you added to the entity)

Basically, my opinon on this subject is that you shouldn't try to pass entities to your business layer. I explained why I think that in a previous answer.

Community
  • 1
  • 1
ken2k
  • 48,145
  • 10
  • 116
  • 176