I have two tables, A and B and a simple table, X, that maintains a relationship between the two. X contains AID and BID as its primary key.
I’m using Linq-to-Sql to insert a relationship like:
public void InsertRelationship(int y, int z) {
DataContext.X.InsertOnSubmit(new x { AID = y; BID = z });
}
The problem is that two calls to InsertRelationship() can be invoked in extreme circumstances so an exception will be thrown due to the duplicate record. This doesn’t matter to me as I know the relationship then exists so I’m ignoring the exception.
Is it okay to ignore an exception in this case or is it still bad practice? Should I check that the relationship doesn’t already exist before the insert? How would this affect performance?
Update
The duplicate call to InsertRelationship() cannot be avoided. It is a web application so I cannot stop the user opening two separate windows and invoking the method twice for example. The method would not be invoked twice through typical user interaction but I’m programming against the extreme case here. The percentage of duplicates will probably be very low but I can’t be sure of exact numbers yet.
The main problem with just ignoring the exception is that an exception may be thrown for other problems not related at all with a duplicate record which you don’t want to hide, like SQL timeouts or deadlocks among others.
The best solution would be to construct your application so the dupes insertion does not happen, the next best would be to check for their existence before doing the insertion.
If performance is critical, the dupes insertion cannot be avoided, the ratio of dupes insertion to working insertion is very small and you can tell that the raised exception is only due to the duplicate problem, you might be better off just catching the exception and ignoring it. But that’s an if with a lot of conditions 🙂