How to update(attach) an entity with children?

How to update(attach) an entity with children?

Postby Sowen » Mon 09 Jan 2012 18:15

Hi

I am trying to figure out if LinqConeect offers an alternate to modify an entity.

In linq to sql, when doing this with a disconnected entity

Code: Select all
context.Attach( entity, original )


will give me "Cannot add an entity with a key that is already in use."

if doing this

Code: Select all
context.Attach (entity, true )


will give me "An entity can only be attached as modified without original state if it declares a version member or does not have an update check policy."

To resolve it, the simplest way was to remove all UpdateCheck or do copy of properties from the modified entity to the in-context entity

However, I still need the concurrency check and I also don't want to do a manual copy because the entity has multiple children.

Another popular way in linq to sql is to detach the entity first, and then attach it back. Well, it has been 4 or 5 years, is there any better neat way now?

Also wondering if linqConnect offers a better alternate to achieve an update like this?

thanks
Sowen
 
Posts: 2
Joined: Mon 09 Jan 2012 17:20

Postby StanislavK » Fri 13 Jan 2012 14:54

Sorry for the delay. Generally, LinqConnect allows updating a disconnected entity in the same way as this is done via LINQ to SQL.

As for the "Cannot add an entity with a key that is already in use." error, the problem is that the row corresponding to this entity was already loaded from the database via this DataContext instance. To overcome this problem, you can, e.g., attach the disconnected entities to a new DataContext instance, and dispose this instance after submitting changes (actually, it is the recommended way of performing update operations to create new DataContext for each unit of work).

To avoid copying data from the entity, and to ensure that its original state corresponds to what is available in the database, you can update an entity in the following way:
Code: Select all
context.Attach(entity);
context.Refresh(System.Data.Linq.RefreshMode.KeepCurrentValues, entity);
context.SubmitChanges();

When an entity is refreshed in such way, it is compared with the corresponding row in the database and marked for updating.

Feel free to contact us if anything is unclear.
StanislavK
Devart Team
 
Posts: 1710
Joined: Thu 03 Dec 2009 10:48


Return to dotConnect for Oracle