I'm experiencing a strange behavior that I really don't know how to work around it. I'm trying to read an entity just after it has been inserted (right after the ExecuteDynamicInsert) and when the partial method returns, I always get a System.Data.Linq.DuplicateKeyException "The database generated a key that is already in use.".
Here is what I'm trying to achieve with a very simple example:
DataContext file MyDataContext.cs:
public partial class MyDataContext
{
public override void SubmitChanges(System.Data.Linq.ConflictMode failureMode)
{
//using (TransactionScope ts = new TransactionScope())
//{
base.SubmitChanges(failureMode);
//}
}
partial void InsertCountry(Country instance)
{
this.ExecuteDynamicInsert(instance);
Country country = this.Countries.Where(c => c.CountryID == instance.CountryID).Single();
} //Exception occurs when this method returns...
}
Program file Program.cs:
class Program
{
static void Main(string[] args)
{
using (MyDataContext dataContext = new MyDataContext())
{
Country c = new Country()
{
Code = "C",
CreatedBy = "Me",
CreatedDate = DateTime.Now,
ModifiedBy = "Me",
ModifiedDate = DateTime.Now
};
dataContext.Countries.InsertOnSubmit(c);
dataContext.SubmitChanges();
}
}
}
If I don't read the country after it has been inserted, the code works fine, but I need to read it for whatever reason and I don't want to use the ChangeSet.
Is there a way to achieve this or to work around this behavior?
Thanks in advance.
I had something like this happen before. Try deleting the Country entity from the DataContext designer and re-adding it.