Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ to SQL - Tracking New / Dirty Objects

Is there a way to determine if a LINQ object has not yet been inserted in the database (new) or has been changed since the last update (dirty)? I plan on binding my UI to LINQ objects (using WPF) and need it to behave differently depending whether or not the object is already in the database.

MyDataContext context = new MyDataContext();
MyObject obj;
if (new Random().NextDouble() > .5)
    obj = new MyObject();
else
    obj = context.MyObjects.First();
// How can I distinguish these two cases?

The only simple solution I can think of is to set the primary key of new records to a negative value (my PKs are an identity field and will therefore be set to a positive integer on INSERT). This will only work for detecting new records. It also requires identity PKs, and requires control of the code creating the new object.

Is there a better way to do this? It seems like LINQ must be internally tracking the status of these objects so that it can know what to do on context.SubmitChanges(). Is there some way to access that "object status"?

Clarification Apparently my initial question was confusing. I'm not looking for a way to insert or update records. I'm looking for a way, given any LINQ object, to determine if that object has not been inserted (new) or has been changed since its last update (dirty).

like image 665
Joseph Sturtevant Avatar asked May 12 '09 18:05

Joseph Sturtevant


1 Answers

ChangeSet changes = context.GetChangeSet();

If changes.Inserts.Contains(yourObject) then it is new and will be inserted when SubmitChanges is called

If changes.Updates.Contains(yourObject), it's already in the database, and will be updated on SubmitChanges()

like image 96
Eivind T Avatar answered Nov 01 '22 00:11

Eivind T