Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get Linq-to-SQL to refresh its local copy of a database record?

Tags:

linq-to-sql

Suppose I have an Orders table in my database and a corresponding model class generated by the VS2008 "Linq to SQL Classes" designer. Suppose I also have a stored procedure (ProcessOrder) in my database that I use to do some processing on an order record.

If I do the following:

var order = dataContext.Orders.Where(o => o.id == orderId).First();

// More code here

dataContext.ProcessOrder(orderId);

order.Status = "PROCESSED";

dataContext.SubmitChanges();

...then I'll get a concurrency violation if the ProcessOrder stored proc has modified the order (which is of course very likely), because L2S will detect that the order record has changed, and will fail to submit the changes to that order.

That's all fairly logical, but what if I want to update the order record after calling the stored proc? How do I tell L2S to forget about its cached copy and refresh it from the DB?

like image 983
Gary McGill Avatar asked Apr 07 '10 13:04

Gary McGill


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.

How does LINQ to SQL work?

In LINQ to SQL, the data model of a relational database is mapped to an object model expressed in the programming language of the developer. When the application runs, LINQ to SQL translates into SQL the language-integrated queries in the object model and sends them to the database for execution.


1 Answers

You can do it with the Refresh method on your data context, like so:

DataContext.Refresh(System.Data.Linq.RefreshMode.OverwriteCurrentValues,
                    DataContext.Orders);
like image 75
Klaus Byskov Pedersen Avatar answered Jan 04 '23 04:01

Klaus Byskov Pedersen