How to use mssqllocaldb in Entity Framework Core 1.1?

.net-core c# entity-framework entity-framework-core unit-testing

Question

How to using the localdb directly with Entity Framework Core? I found many demo is just for asp.net core. But not for console or unittest direct.

Demo code :

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
    // Add framework services.
    services.AddMvc();

    var connection = @"Server=(localdb)\mssqllocaldb;Database=EFGetStarted.AspNetCore.NewDb;Trusted_Connection=True;";
    services.AddDbContext<BloggingContext>(options => options.UseSqlServer(connection));
}

My code :

_fixture.SqlConnectionStr=@"Server=(localdb)\\mssqllocaldb;Database=DailyDbContext;Trusted_Connection=True;MultipleActiveResultSets=true"

var connection = new SqlConnection(_fixture.SqlConnectionStr);
connection.Open();

// Create the schema in the database
using (var context = new DailyDbContext(options))
{
    context.Database.EnsureCreated();
}

Throws an exception as follows:

Stack:

at System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, Object providerInfo, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData reconnectSessionData, Boolean applyTransientFaultHandling)
at System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions)
at System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnectionPool pool, DbConnection owningObject, DbConnectionOptions options, DbConnectionPoolKey poolKey, DbConnectionOptions userOptions)
at System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)
at System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)
at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection)
at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection)
at System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbConnectionInternal& connection)
at System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)
at System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry)
at System.Data.SqlClient.SqlConnection.Open()
at HQF.Tutorials.EntityFrameworkCore.XUnitTest.UnitTest1.Test1() in 

 System.Data.SqlClient.SqlException : A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 50 - Local Database Runtime error occurred. 指定的 LocalDB 实例名称无效。

But sqlite works just fine:

 // In-memory database only exists while the connection is open
 var connection = new SqliteConnection("DataSource=:memory:");

 var options = new DbContextOptionsBuilder<DailyDbContext>()
                .UseSqlite(connection)                   
                .Options;

            // Create the schema in the database
            using (var context = new DailyDbContext(options))
            {
                context.Database.EnsureCreated();
            }
1
1
7/29/2017 5:41:06 AM

Accepted Answer

I found that is working right.

public SimpleIntegrationTest()
{
    var serviceProvider = new ServiceCollection()
        .AddEntityFrameworkSqlServer()
        .BuildServiceProvider();

    var builder = new DbContextOptionsBuilder<MonsterContext>();

    builder.UseSqlServer($"Server=(localdb)\\mssqllocaldb;Database=monsters_db_{Guid.NewGuid()};Trusted_Connection=True;MultipleActiveResultSets=true")
            .UseInternalServiceProvider(serviceProvider);

    _context = new MonsterContext(builder.Options);
    _context.Database.Migrate();

}
1
7/29/2017 3:20:11 PM


Related Questions





Related

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