Value cannot be null: connection while testing database c# entity-framework-6 sql-server


I'm trying to run integration tests for my ASP.NET MVC application using Entity Framework 6.

The error I get is

System.Data.Entity.Core.EntityException: The underlying provider failed on Rollback. ---> System.ArgumentNullException: Value cannot be null.
Parameter name: connection

The code looks like this:

Database.SetInitializer(new PrimaryInitializerTest());
_context = new PrimaryContextTest();

using (var dbt = _context.Database.BeginTransaction())

I also tried having an dbt.UnderlyingTransaction.Connection.Open() call just below the using statement, and a dbt.UnderlyingTransaction.Connection.Close() call just below the call to Rollback(). That gave me the error Connection is not closed.

PrimaryInitializerTest class

protected override void Seed(PrimaryContextTest context)
    // (...) Input some values

PrimaryContextTest class

public class PrimaryContextTest : DbContext
    public PrimaryContextTest() : base("PrimaryContextTest")
        Database.SetInitializer(new DropCreateDatabaseAlways<PrimaryContextTest>());

    public DbSet<Story> Stories { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)

Connection string

<add name="PrimaryContextTest" 
     connectionString="Data Source=(LocalDb)\mssqllocaldb;Initial Catalog=PrimaryContextTest;Integrated Security=SSPI;AttachDbFilename=|DataDirectory|\PrimaryContextTest.mdf" 
     providerName="System.Data.SqlClient" />

Context string

<context type="fcon.DAL.Tests.PrimaryContextTest, fcon, Version=, Culture=neutral">
    <databaseInitializer type="fcon.DAL.Tests.PrimaryInitializerTest, fcon" />

What could I be doing wrong?

Might mention that the database doesn't exist in the App_Data folder...

1/4/2016 5:08:24 AM

Popular Answer

You're calling Commit and then Rollback, but the comments point that mistake out.

The error isn't very intuitive, I mean, an ArgumentNullException should never work its way out of an SDK from down the stack.

But I've had this when I've accidentally reused the same transaction instance, or called Commit twice, or tried to rollback twice in layered error recovery logic.

5/6/2016 3:29:58 PM

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow