Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ to SQL - updating records

Tags:

sql

asp.net

linq

Using asp.net 4 though C#.

In my data access layer I have methods for saving and updating records. Saving is easy enough but the updating is tedious.

I previously used SubSonic which was great as it had active record and knew that if I loaded a record, changed a few entries and then saved it again, it recognised it as an update and didn't try to save a new entry in the DB.

I don't know how to do the same thing in LINQ. As a result my workflow is like this:

  1. Web page grabs 'Record A' from the DB
  2. Some values in it are changed by the user.
  3. 'Record A' is passed back to the data access layer
  4. I now need to load Record A again, calling it 'SavedRecord A', update all values in this object with the values from the passed 'Record A' and then update/ save 'SavedRecord A'!

If I just save 'Record A' I end up with a new entry in the DB.

Obviously it would be nicer to just pass Record A and do something like:

RecordA.Update();

I'm presuming there's something I'm missing here but I can't find a straightforward answer on-line.

like image 312
Full Time Skeleton Avatar asked Jul 02 '12 15:07

Full Time Skeleton


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.

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 converted to SQL?

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.

Which is better Entity Framework or LINQ to SQL?

First off, if you're starting a new project, use Entity Framework ("EF") instead of Linq to SQL because it now generates far better SQL (more like Linq to SQL does) and is easier to maintain ("L2S").


1 Answers

You can accomplish what you want using the Attach method on the Table instance, and committing via the SubmitChanges() method on the DataContext.

This process may not be as straight-forward as we would like, but you can read David DeWinter's LINQ to SQL: Updating Entities for a more in depth explanation/tutorial.

like image 134
smartcaveman Avatar answered Sep 28 '22 18:09

smartcaveman