Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I tell if a linq to sql object is new, modified or unchanged?

I have a single linq to sql class. I would like to detect if it is new (meaning an insert will be done) or if there are any pending changes (update will be done). I realize that I can do this by using a partial class and hooking into the on change events for each property. However that is a lot of maintenance for a class that is constantly changing.

Is there a better way?

like image 548
Jason Webb Avatar asked Jun 02 '10 19:06

Jason Webb


People also ask

Does LINQ select return new object?

While the LINQ methods always return a new collection, they don't create a new set of objects: Both the input collection (customers, in my example) and the output collection (validCustomers, in my previous example) are just sets of pointers to the same objects.

Is LINQ to SQL deprecated?

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.

How do you update a record in LINQ?

You can update rows in a database by modifying member values of the objects associated with the LINQ to SQL Table<TEntity> collection and then submitting the changes to the database. LINQ to SQL translates your changes into the appropriate SQL UPDATE commands.

What is LINQ why is it used give an example for the same?

LINQ queries return results as objects. It enables you to uses object-oriented approach on the result set and not to worry about transforming different formats of results into objects. The following example demonstrates a simple LINQ query that gets all strings from an array which contains 'a'.


1 Answers

You can check through the DataContext class.

First, check the ObjectTrackingEnabled property on the DataContext. If it returns false, then the object is not being tracked by the context.

Then, call the GetChangeSet method on the DataContext. From there, compare the references exposed by the Deletes, Updates, and Inserts properties against your object.

If the reference is found in any of those lists, then your object is being tracked by that list and you can proceed from there.

like image 69
casperOne Avatar answered Oct 03 '22 05:10

casperOne