Can I check that Linq 2 SQL DataContext is tracking objects?

We want to throw an exception if the user calls DataContext.SubmitChanges () and the DataContext is not tracking anything.

That is ... it's okay to call SubmitChanges if there are no inserts, updates, or deletes. But we want to make sure the developer didn't forget to attach the object to the DataContext.

Better yet ... is it possible to get a collection of all the objects that the DataContext is tracking (including those that haven't changed)?

PS: the last question I asked answered "do it like this" please don't do it :-)

0


source to share


3 answers


I don't think there are any public / protected methods that will allow you to get this straight. You will probably have to use reflection, for example I did about 3 posts in here looking at the property ChangeTracker

Services

, very ugly, I'm afraid.



+1


source


Have a look at ObjectTracker or whatever the DataContext hangs. It has a list of the changes stored in it.



Also, I believe SubmitChanges is virtual, so you can intercept the SubmitChanges call and do some validation there.

0


source


If I understood the question correctly ...

This shows you what the DataContext is tracking

DataContext.GetChangeSet().Inserts;
DataContext.GetChangeSet().Deletes;
DataContext.GetChangeSet().Updates;

      

Is this what you are thinking?

if (DataContext.GetChageSet().Inserts.Count = 0
        && DataContext.GetChageSet().Deletes.Count
        && DataContext.GetChageSet().Updates.Count)
{
    throw new Exception("You forgot to do something with your DataContext...");
}
else
{
    DataContext.SubmitChanges();
}

      

0


source







All Articles