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

huoxudong125

如何在 Entity Framework Core 中直接使用 localdb?我发现许多演示仅适用于 asp.net 核心。但不适用于控制台或单元测试直接。

演示代码:

// 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));
}

我的代码:

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

抛出异常如下:

堆:

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

我发现这是正确的。

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

}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何使用Net Topology Suite在Entity Framework Core中缓冲1米的点(地理)

如何在领域驱动设计中使用 Entity Framework Core 处理包含

如何在Entity Framework Core中使用循环依赖关系正确播种数据?

如何在.NET Core 1.0中使用Entity Framework运行SQL脚本?

如何在Entity Framework Core的复合键中使用常量配置关系?

如何在dotnet core中使用Entity Framework进行数据获取

如何在Entity Framework Core中使用VARCHAR或NVARCHAR自动增加ID?

如何在Entity Framework Core 2.0的模型内部使用OnModelCreating?

在Entity Framework Core中使用[ComplexType]

在Entity Framework Core中使用迁移

如何在Visual Studio 2019中使用Entity Framework Core将实体模型添加到.Net Core ClassLibrary?

如何在Entity Framework Core中使用Join()方法将Sql查询转换为Linq及其等效项

如何在Azure Function v1(.NET Framework)中使用Azure App配置服务

如何在Linq Entity Framework C#中使用if语句

如何在Entity Framework中使用主键查找数据?

如何在Entity Framework中使用unsigned int / long类型?

如何在Asp.net Core rc1中的静态方法中使用DI

如何在ASP.NET Core 1和VSCode编辑器中使用WCF服务?

如何在Entity Framework Code First中实现1..n双向关系

如何在ASP.NET Core Web应用程序中使用Entity Framework Core从数据库保存和检索图像?

在 LINQ to Entity Framework Core 中使用表达式树

在SQL CLR中使用Entity Framework 6 / EF Core

在FromSql Entity Framework Core方法中使用内部联接

在Entity Framework Core中使用动态过滤器

如何在Visual Studio Code中安装和使用Entity Framework Core?

使用 Entity Framework Core 5,如何在调用 SaveChanges() 时自动更新相关实体?

如何使用 FromSqlRaw 在 Entity Framework Core 中返回 int 列表?

如何使用Entity Framework Core进行全文搜索?

如何使用Entity Framework Core加载相关实体