Search code examples
c#entity-framework-6sql-server-2012-express

Entity Framework 6 BulkInsert receiving an invalid column length from the client SQL SERVER 2012 Express


I have a little problem with Entity Framework 6.

My application is a WPF C# application, I use SQL SERVER 2012 Express.

I try to insert data into my Person table.

It was working for a long time. Today I had an error : receiving an invalid column length from the client 46.

I searched and found some articles, they are talking about column sizes etc but in my case, tis is not the problem.

This code was working : dc.BulkInsert(listToInsert, options);

  **using EntityFramework.BulkInsert.Extensions;**


     //I have a list of person object to insert.
     var listToInsert = PersonList.Where(ro => !ExistingPerson.Contains(ro.Pers_Code.ToLower())).ToList();


 using(MyEntities dc = new MyEntities())
 {
   *//If I add items one by one, it works*
   foreach (var item in listToInsert)
   {
     dc.Person.Add(item);
   }
   dc.SaveChanges(); //Success.


    //But If I use Bulkinsert, I have an error message 

   BulkInsertOptions options = new BulkInsertOptions();
   options.BatchSize = 1000;
   dc.BulkInsert<Person>(listToInsert, options); // at this moment I have this error message : receiving an invalid column length from the client 46.


    dc.SaveChanges();
 }

I checked the data length of items, I didn't see any problem.

Does anyone have an idea ?

Thanks.


Solution

  • The SaveChanges use a SqlCommand. If the name is longer than the database limit, it will silently be truncated, so no error will be thrown.

    The BulkInsert use a SqlBulkCopy, if the name is longer than the database limit, an error will be thrown.

    That explain why you get an error in one case and none in the other case.

    SqlBulkCopy doesn't raise this error for fun, so I would double check your length with your column size.

    • Perhaps the type is char(xyz) and there is space at the end?
    • Perhaps there is some space at the start?
    • etc.

    .NET Fiddle support Entity Framework and NuGet packages. So, if you could reproduce it online, it could be possible to tell exactly why that happens.

    Example: https://dotnetfiddle.net/35mQ0W