简体   繁体   English

实体框架核心 DbContext 设置 DbConnection

[英]Entity Framework Core DbContext set DbConnection

In .NET Framework was DbContext in EntityFramework 6 was constructor where I can set DbConnection.在 .NET 框架中是 DbContext,在 EntityFramework 6 中是构造函数,我可以在其中设置 DbConnection。

In EF .NET Core can I set DbContext DbConnection?在 EF .NET Core 中,我可以设置 DbContext DbConnection 吗? I hit an exception in UseTransaction of DbContext method:我在 DbContext 方法的 UseTransaction 中遇到异常:

An exception of type 'System.InvalidOperationException' occurred in Microsoft.EntityFrameworkCore.Relational.dll but was not handled in user code: 'The specified transaction is not associated with the current connection. Microsoft.EntityFrameworkCore.Relational.dll 中发生了“System.InvalidOperationException”类型的异常,但未在用户代码中处理:“指定的事务与当前连接无关。 Only transactions associated with the current connection may be used.'只能使用与当前连接关联的事务。

Does any body know how set the DbConnection?有谁知道如何设置 DbConnection? Or I have get a wrong way?还是我走错路了?

I have always added the Database Context within the startup file of .Net core apps by adding it to the IServiceCollection and pulling the string from the appsetting file like so: 我一直将.NET核心应用程序的启动文件添加到数据库上下文中,方法是将其添加到IServiceCollection并从appsetting文件中拉出字符串,如下所示:

        private void AddDatabase(IServiceCollection services)
    {
        var databaseConnectionString = Configuration.GetConnectionString("DatabseConnection");

        Check.CanConnectToDatabase(databaseConnectionString);

        services.AddDbContext<DatabaseContext>(
            options =>
            {
                options.ConfigureWarnings(
                    warnings => warnings.Throw(RelationalEventId.QueryClientEvaluationWarning));
                options.UseSqlServer(databaseConnectionString,
                    sqlOptions => sqlOptions.MigrationsHistoryTable(HistoryRepository.DefaultTableName, "SchemaName"));
            });
    }

If I understand correctly, you can not create DbConnection because it's a protected class hence you should get DbConnection then you set the connection string and finally set your DbCollection.如果我理解正确,则无法创建DbConnection ,因为它是受保护的 class 因此您应该获取 DbConnection,然后设置连接字符串,最后设置 DbCollection。

var dbConnection =  (await GetDbContextAsync()).Database.GetDbConnection();
dbConnection.ConnectionString = "yourConnectinString";
(await GetDbContextAsync()).Database.SetDbConnection(dbConnection);
//Also you can test your connection
await (await GetDbContextAsync()).Database.CanConnectAsync();

Maybe it's a tricky way but it worked for me.也许这是一种棘手的方式,但它对我有用。 Regards问候

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM