I have two SQL tables, each with a compound key made of three different integer fields. I have added the code as follows to add a record to Table1.
try
{
Table1 newRow = new Table1
{
DomainID = domainID,
ConfigurationID = configID,
ReasonID = reasonID
};
data.Table1.InsertOnSubmit(newRow);
data.SubmitChanges();
}
catch(DuplicateKeyException)
{
// Message to user about no duplicates allowed.
}
This works exactly how I have planned and catches an exception if the user is trying to add a duplicate row and I can show them a message etc. All is fine. However, the code I have for inserting to Table2 (which is almost identical, on a different Page using a different DataContext however),
try
{
Table2 newRow = new Table2
{
DomainID = domainID,
ConfigurationID = configID,
DirectionID = directionID
};
data.Table2.InsertOnSubmit(newRow);
data.SubmitChanges();
}
catch(DuplicateKeyException)
{
// Message to user about no duplicates allowed.
}
does not throw a DuplicateKeyException but a SqlException. Not too much of a big-deal as I can still test
e.Number = 2627
on the caught SqlException but I’m just confused as to why it is working differently!?
There must be a problem with the definition of your table 2. Specifically with the primary key column on it. Maybe it has a Unique Constraint and that’s why it throws an exception, but it is not certainly its primary key.