Suppose I have a table with PK column, some other columns, and one which must be unique.
Which approach would be better for handling the possibility that new record is being added with unique key that already exists?
Query db e.g.
if (!_db.MyTable.Any(mt => mt.UniqueCode == newRecord.UniqueCode))
_db.MyTable.Add(newRecord);
else //handle response
or try to add it without checking and handle the error? e.g.
try
}
_db.MyTable.Add(newRecord);
}
catch (Exception e)
{
//handle response
}
In the first approach the downside I see is that it requires 2 calls to db. (I left _db.SaveChanges()
out), but I'v always felt that it's better to avoid exceptions. How is it? Which one would be better for performance? Is there a better way?