gpt4 book ai didi

c# - 为什么我不能将 ServiceStack Ormlite 连接转换到 SqlConnection?

转载 作者:行者123 更新时间:2023-11-30 20:47:01 24 4
gpt4 key购买 nike

我正在尝试将 SqlBulkCopyServiceStack Ormlite 一起使用,并编写了以下扩展方法:

public static void BulkInsertSqlServer<T>(this IDbConnection dbConn, string targetTable, IEnumerable<T> data, params string[] columns)
{
Ensure.NotNull(dbConn);
Ensure.That(dbConn.State == ConnectionState.Open);
Ensure.NotNullOrEmptyOrWhiteSpace(targetTable);
Ensure.NotNull(data);
Ensure.NotNullOrEmpty(columns);

var sqlConnection = dbConn as SqlConnection;

using (var bcp = new SqlBulkCopy(sqlConnection))
using (var reader = ObjectReader.Create(data, columns))
{
bcp.BatchSize = data.Count();
bcp.DestinationTableName = targetTable;
bcp.WriteToServer(reader);
}
}

我正在使用:

_connFactory = new OrmLiteConnectionFactory(connStr, SqlServerOrmLiteDialectProvider.Instance);

using (var db = _connFactory.Open())
using (var tran = db.BeginTransaction())
{
db.BulkInsertSqlServer("User", users, "Name", "Age");

var allRoles = new List<Role>();

foreach (var listOfRoles in users.Select(d => d.Roles))
{
allRoles.AddRange(listOfRoles);
}

db.BulkInsertSqlServer("Role", allRoles, "Name", "UserId", "IsAdmin");

tran.Commit();
}

但是 sqlConnection 总是空的,有什么想法吗?

最佳答案

因为连接被包装在托管的 OrmLiteConnectionWrapper 中,您可以通过以下方式获取 SqlConnection:

var adoNetConn = ((IHasDbConnection)dbConn).DbConnection;    
var sqlConnection = adoNetConn as SqlConnection;

关于c# - 为什么我不能将 ServiceStack Ormlite 连接转换到 SqlConnection?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26179533/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com