Here a small piece of code for testing and explain the problem. I have a table Person with 3 fields :
- Id
- FirstName (not nullable)
- LastName (not nullable)
In the loop :
- First : I insert the first row … normal,
- Second : I try to insert a not correct item,
Exception… normal - Third : I try to insert the third row …
Exception(same than for the second) but the values are correct.
Is there something to do to use the same dataContext after an Exception ?
public class MyTestClass
{
private readonly DataModelDataContext _dataContext;
public MyTestClass()
{
_dataContext = new DataModelDataContext();
}
public void InsertList()
{
List<Person> liste = new List<Person>();
liste.Add(new Person { FirstName = "AAA", LastName = "BBBB" });
liste.Add(new Person { FirstName = string.Empty, LastName = null });
liste.Add(new Person { FirstName = "CCC", LastName = "DDD" });
foreach (var item in liste)
{
try
{
_dataContext.Persons.InsertOnSubmit(item);
_dataContext.SubmitChanges();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
}
The
DataContextshould always be short-lived. You should re-factor your design to achieve this.You can consider these points:
usingstatement.Remark from MSDN:
If it takes time to re-factor your design, temporarily you can do like this:
and this is how you can call
InserListMethod: