我正在尝试将SqlBulkCopy
与ServiceStack 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
总是空的,有什么想法吗?
答案 0 :(得分:4)
因为连接包装在托管OrmLiteConnectionWrapper中,所以可以使用以下命令获取SqlConnection:
var adoNetConn = ((IHasDbConnection)dbConn).DbConnection;
var sqlConnection = adoNetConn as SqlConnection;