In .NET 4.0 and Linq to SQL, I am trying to use a partial class to “trigger” changes from within an update method (an existing DBML method). For simplicity, imagine a table Things with columns Id and Value
The auto gen DBML contains a method OnValueChanged, I’ll extend that and as an exercise try to change one value in one other row :
public partial class Things
{
partial void OnValueChanged()
{
MyAppDataContext dc = new MyAppDataContext();
var q = from o in dc.GetTable<Things>() where o.Id == 13 select o;
foreach (Things o in q)
{
o.Value = "1"; // try to change some other row
}
try
{
dc.SubmitChanges();
}
catch (Exception)
{
// SQL timeout occurs
}
}
}
A SQL timeout error occurs. I suspect that the datacontext is getting confused trying to SubmitChanges() before the current OnValueChanged() method has disposed of it’s datacontext, but I am not sure.
Mostly I cannot find an example of a good pattern for triggering updates against a DB within an existing DBML generated method.
Can anyone provide any pointers on why this doesn’t work and how I can accomplish something that works OK? (I realize I can trigger in the SQL database, but do not want to take that route.)
Thanks!
First, you aren’t disposing of the
DataContextat all in your function. Wrap it in ausingstatement.The actual issue is coming from the fact that you’re recursively calling yourself by setting the
Valueproperty on the retrieved values. You’re just running into the timeout before you can hit aStackOverflowException.It’s unclear what you’re trying to do here; if you’re trying to allow different behavior between when you set the
Valueproperty here versus anywhere else, then it’s simple enough to use a flag. In your partial class, declare aninternalinstance boolean auto property calledUpdatingValue, and set it totrueon each item inside yourforeachblock before you update the value, then set it tofalseafter you update the value. Then, as the first line inOnValueChanged, check to ensure thatUpdatingValueisfalse.Like this: