Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to update in Linq To SQL

I have several entity classes that I use for parsing fixed width text files as well as utilizing Linq to SQL. I use these classes to parse data from said text files, and compare to data in the database.

One of these entities has a lot of properties, and I don't want to waste time setting each individual property on the Linq result object.

Is there a way to tell Linq "Here's my object, use this to update the record"? Here's code I'm working on:

if (partialContent.MonthlyAddChange == "A")
   {
       bookContentTable.InsertOnSubmit(partialContent);
   }
   else if (partialContent.MonthlyAddChange == "C")
   {
       var query = from bookContent in bookContentTable
                   where bookContent.EAN == partialContent.EAN
                   select bookContent;

       if (query != null)
       {
           // Do something with query.First()
       }
   }
}

Is it better to delete the record and do an InsertOnSubmit() in this case?

like image 680
James Avatar asked Mar 20 '09 20:03

James


People also ask

How do you update a record in LINQ?

To update a row in the databaseQuery the database for the row to be updated. Make desired changes to member values in the resulting LINQ to SQL object. Submit the changes to the database.

How does a LINQ query transform to a SQL query?

LINQ to SQL translates the queries you write into equivalent SQL queries and sends them to the server for processing. More specifically, your application uses the LINQ to SQL API to request query execution. The LINQ to SQL provider then transforms the query into SQL text and delegates execution to the ADO provider.

Is LINQ to SQL obsolete?

LINQ to SQL was the first object-relational mapping technology released by Microsoft. It works well in basic scenarios and continues to be supported in Visual Studio, but it's no longer under active development.

Is LINQ faster than SQL?

Sql is faster than Linq. Its simple: if I m executing a sql query directly its a one way process whereas if I m using linq, first its been converted to sql query and then its executed.


2 Answers

I think the concept of editing a record is different from deleting and inserting a new one. Basically, I think an ORM should abstract away primary key generation and other related stuff. By deleting and inserting, you might be removing the integrity of the record (probably issuing a new primary key, making referenced entities invalid and so forth...). I suggest updating the record whenever the action you are taking is conceptually an update.

like image 141
mmx Avatar answered Oct 11 '22 14:10

mmx


You can consider using automapper to copy the values for you. Check this for more info: http://www.lostechies.com/blogs/jimmy_bogard/archive/2009/01/22/automapper-the-object-object-mapper.aspx

like image 40
eglasius Avatar answered Oct 11 '22 13:10

eglasius