Search code examples
c#ef-bulkinsert

c# bulkinsert MSSQL Object reference not set to an instance of an object weird issue


I've got a weird issue I've been trying to solve.

BulkInsert works in one database but not another, even with identical tables. Visual Studio 2017, c#. I've used reverse poco to build the entity framework files.

The SQL table in each db consists of simply:

CREATE TABLE [dbo].[BulkInsertTest](
  [id] [int] NOT NULL,
  [name] [varchar](50) NOT NULL,
CONSTRAINT [PK_BulkInsertTest] PRIMARY KEY CLUSTERED 
(
[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, 
ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO

The C# code is simply:

using (GISDbContext db = new GISDbContext())
{
  List<BulkInsertTest> sqlFormattedRecords = new List<BulkInsertTest>();
    for (int i = 20; i < 40; i++)
    {
        BulkInsertTest record = new BulkInsertTest();
        record.Id = i;
        record.Name = $"NameIs{i}";
        sqlFormattedRecords.Add(record);
     }

     // Insert the newly loaded records into the  table
     using (var transactionScope = new TransactionScope())
     {
         db.BulkInsert(sqlFormattedRecords);
         db.SaveChanges();
         transactionScope.Complete();
     }
}

When I point this same code to the one database, it works. When I point it to the other database, it doesn't. It fails with a null pointer exception in the bulkinsert function:

at EntityFramework.BulkInsert.ProviderFactory.Get(DbContext context)

So then I tried recreating the second one to use the first db's connection string. The second set of reverse poco tt file is literally a copy of the first db's tt file with the context name changed to GISDbContext.

You would think this would work. It doesn't. Same error.

Switching the code back to using the first reverse poco dbcontext still works though.

So it's not the connection string. It's not the reverse poco .tt file. It's not the database or the table. But I'm not sure what the problem is caused by.

Edit: so currently I removed the second (non-working) reverse poco tt files and tried updating the first one to see where it would crash. Everything worked until I tried changing the DbContextName. When I did that, it breaks. Doesn't matter what i change it to, if it's not the original context name I used for the working tt file, it crashes.

This makes absolutely no sense to me.

I tried cleaning the solution (one project in this solution). I tried clearing out the obj/bin folders after cleaning the solution. No effect. It's crazy.


Solution

  • This is sort of a duplicate. I simplified the code to narrow down what was happening, and posted it again, because I don't think people were bothering with this one.

    The solution turned out to make the dbcontext name the same as the connection string name. Thank you Fakhar.