EF CodeFirst handles database exceptions when saving changes

Since EF does not support unique key constraints, it seems that we need to catch an exception during the Save method and display an error message to the user.

Problems with this approach:

  • how do we know which record made an exception.
  • How do we find out what problem caused the exception (for example, I could have two unique restrictions on the same record, so I need to tell the user which one is damaged)

DBMS is SqlServer 2008.

How to solve these problems?

+5
source share
1 answer

, , :

if (context.Customers.Any(c => c.SomeUniqueProperty == userInput))
    // return to user with a message to change the input value
else
    context.SaveChanges();

, , , . EF , , , . , EF , . .

, Any SaveChanges , , . " , , ...". Any, , .

, , DbUpdateException, SqlException, SQL Server. " UNIQUE KEY IX_SomeUniqueProperty_Index..." . , , . , .

+2

All Articles