How to Find Column Causing “String or binary data would be truncated” Exception in Entity Framework 5.0.

1 Comment

I recently encountered an issue with Entity Framework when it would throw “String or binary data would be truncated. The statement has been terminated.” Since the query contained close to 80 fields, I needed an easy way to determine the culprit. Since I already had a class which inherits from DbContext, I added suggested try-catch block in my SaveChanges() override method:

public partial class MyContext : DbContext
	{
		public override int SaveChanges()
		{
			try
			{
				return base.SaveChanges();
			}
			catch (DbEntityValidationException ex)
			{
				foreach (var error in ex.EntityValidationErrors)
				{
					Console.WriteLine("====================");
					Console.WriteLine(
						"Entity {0} in state {1} has validation errors:",
						error.Entry.Entity.GetType().Name,
						error.Entry.State);
					foreach (var ve in error.ValidationErrors)
					{
						Console.WriteLine("\tProperty: {0}, Error: {1}", ve.PropertyName, ve.ErrorMessage);
					}
					Console.WriteLine();
				}
				throw;
			}
		}
	}

You have to make sure that you don’t set ValidateOnSaveEnabled to false. It is set to true by default, but sometimes it is useful to disable it to improve performance.

Categories: C#, Entity Framework Tags: Tags:

One Reply to “How to Find Column Causing “String or binary data would be truncated” Exception in Entity Framework 5.0.”

  1. I’m getting the “STRING OR BINARY DATA WOULD BE TRUNCATED” error too but I’m not getting a DbEntityValidationException exception. I’m getting a System.Data.UpdateException. I’m not even updating a record, I’m only inserting so I don’t know why I’m getting an update error.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Loading Facebook Comments ...