How to Debug SQL Exception: String or Binary Data Would Be Truncated in .NET EF Core

While building a new application for an old database, I ran into an issue where I was too trying update a column with to long of a string. Entity Framework gives an error similar to String or binary data would be truncated. The statement has been terminated. This error message is rather useless if your database has a lot of columns.

If you're using Entity Framework, you can wrap your Save method in a try-catch to add more information.


try {
  await _context.SaveChangesAsync();
}catch(Exception ex){
  var entries = _context.ChangeTracker.Entries().Where(e => e.State != EntityState.Unchanged);
  foreach(var entry in entries){
    foreach(var prop in entry.CurrentValues.Properties){
      var val = prop.PropertyInfo.GetValue(entry.Entity);
      Console.WriteLine($"{prop.ToString()} ~ ({val?.ToString().Length})({val})");
    }
  }
}

You can view your terminal and spot the entity that's too long.

One Last Thing...

If you have a question or see a mistake, please comment below.

If you found this post helpful, please share it with others. It's the best thanks I can ask for & it gives me momentum to keep writing!

Matt Ferderer
Software Developer focused on making great user experiences. I enjoy learning, sharing & helping others make amazing things.
Let's Connect