Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ to SQL - entity properties - overwriting one entity with another

Tags:

c#

linq-to-sql

First, a little background. I have a DataContext object (Linq to SQL). I use this to interact with my SQL database. I'm using C# in Visual Studio 2010.

The problem is this: I can edit an entry from an entity table that I want. I select the entity with a query, change the particular field, then submit the data context changes. But let's say that I get a separate entity. This entity is actually an edited version of one of the existing entities. So what wants to happen is for this one to overwrite that one. Now, yes, this is possible. You check the primary key, and overwrite the fields from the old one with the fields of the new one. So where's the problem? The problem is if the entity has 40+ fields, it's a pain to assign each field individually. Is there no method or way of doing this more quickly?

Thanks.

like image 754
user738383 Avatar asked Oct 10 '22 06:10

user738383


1 Answers

You can use the Attach() method. If an entity with the same ID already exists in the database, it will be overwrirtten with the attached entity.

myDataContext.Customers.Attach(myCustomer);
myDataContext.SubmitChanges();
like image 139
Dennis Traub Avatar answered Oct 13 '22 12:10

Dennis Traub