So I am having a problem catching the exception for adding a new record to the database.
I am using Entity Framework
Here is my code:
public void AddNewStandardEngineeredModel(StandardEngineeredModel model)
{
using (context = new LabelPrintingContext())
{
try
{
context.EngineeredModels.Add(model);
context.SaveChanges();
}
catch (SqlException ex)
{
if (ex.Number == 2601)
{
//Violation of primary key. Handle Exception
}
else throw;
}
}
}
I have also tried the following:
public void AddNewStandardEngineeredModel(StandardEngineeredModel model)
{
using (context = new LabelPrintingContext())
{
try
{
context.EngineeredModels.Add(model);
context.SaveChanges();
}
catch (UpdateException ex)
{
var sqlException = ex.InnerException as SqlException;
if (sqlException != null && sqlException.Errors.OfType<SqlError>()
.Any(se => se.Number == 2601))
{
// it's a dupe... do something about it
}
else
{
// it's something else...
throw;
}
}
}
}
If I just do catch(Exception Ex) it will catch the exception but I want to check the number to give a better response to my user. That way if a duplicate is about to be added I can let them know and fix it appropriately.
Here is a picture of the error:
Not quite sure what else to try and catch the specific exception. Any suggestions would help.