Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/259.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何在Entity Framework Core 1.1中使用mssqllocaldb?_C#_Entity Framework_Unit Testing_.net Core_Entity Framework Core - Fatal编程技术网

C# 如何在Entity Framework Core 1.1中使用mssqllocaldb?

C# 如何在Entity Framework Core 1.1中使用mssqllocaldb?,c#,entity-framework,unit-testing,.net-core,entity-framework-core,C#,Entity Framework,Unit Testing,.net Core,Entity Framework Core,如何将localdb直接与实体框架核心一起使用?我发现很多演示都是针对asp.net核心的。但不适用于console或unittest direct 演示代码: // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { // Add fram

如何将localdb直接与实体框架核心一起使用?我发现很多演示都是针对asp.net核心的。但不适用于console或unittest direct

演示代码:

// 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));
}
引发异常,如下所示:

堆栈:

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 实例名称无效。
但是sqlite工作得很好:

 // 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();
            }
//内存中数据库仅在连接打开时存在
var connection=newsqliteconnection(“数据源=:内存:”);
var options=new DbContextOptionsBuilder()
.UseSqlite(连接)
.选择;
//在数据库中创建模式
使用(var context=newdailydbcontext(选项))
{
context.Database.recreated();
}

我发现它工作正常

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();

}
public SimpleIntegrationTest()
{
var serviceProvider=newservicecolection()
.AddEntityFrameworkSqlServer()
.BuildServiceProvider();
var builder=new DbContextOptionsBuilder();
builder.UseSqlServer($“Server=(localdb)\\mssqllocaldb;Database=monsters\u db\u{Guid.NewGuid()};Trusted\u Connection=True;MultipleActiveResultSets=True”)
.UseInternalServiceProvider(服务提供商);
_上下文=新上下文(builder.Options);
_Migrate();
}

下面是一个例子,描述了SqlLocalDb连接字符串的一个常见问题:根据SqlLocalDb的版本,连接字符串必须略有不同。这可能是您的问题,也可能不是您的问题,但无论如何都很容易尝试。您在此处的连接字符串中有一个输入错误
Server=(localdb)\\mssqllocaldb
。当使用逐字字符串时,您不应双击
“\”
@lvan Stoev,它将引发异常`System.Data.SqlClient.SqlException:无法打开登录请求的数据库“daily\u db\u Test”。登录失败。用户“FRANK-PC\FRANK”登录失败。`@IvanStoev正确。您在上面看到的异常是因为您的连接字符串不正确。按照Ivan的建议更新字符串后,您出现登录失败错误,因为您的数据库不存在,您对其调用了connection.Open()。请解释您的解决方案的关键部分,使其对未来的读者更有价值。@GertArnold是的,我会找到更多详细信息。
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();

}