How would I know which field causing DbUpdateException in Entity Framework 7 ?

Victor Cherniavsky 20 Reputation points
2023-06-23T14:12:33.1466667+00:00

How can I get in C# the entity and the field causing DbUpdateException in Entity Framework 7 when saving to SQL Server ?

Developer technologies | .NET | Entity Framework Core
{count} votes

Answer accepted by question author
  1. Wenbin Geng 746 Reputation points Microsoft External Staff
    2023-06-29T03:18:32.3733333+00:00

    Hi @Victor Cherniavsky, Welcome to Microsoft Q&A.

    DbUpdateException contains update failures in many cases, and it is difficult to obtain the failed fields at one time. Currently using C# to obtain fields that fail to be updated, you can change the code as follows:

                 try
                 {
                     using Db db = new Db();
                     T_Row row = db.T_Rows.Single(e=>e.id == 123)
                     row.f1 = ...;
                     db. SaveChanges();
                     row.f2 = ...;
                     db. SaveChanges();
                     row.fn =  …;
                     db. SaveChanges();
                 }
                 catch (DbUpdateException ex)
                 {
                    var failedEntries = ex.Entries;
                         foreach (var entry in failedEntries)
                         {
                             var entityName = entry. Metadata. Name;
                             var properties = entry.Properties.Where(p => p.IsModified && !p.IsTemporary);
                             foreach (var property in properties)
                             {
                                 var propertyName = property.Metadata.Name;
                                 Console.WriteLine($"Failed to update field: {propertyName} in entity: {entityName}");
                             }
                         }
                 }
    
    
    
    

    Best Regards,

    Wenbin


    If the answer is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.  


0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.