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).