为什么我不能将ServiceStack Ormlite连接转换为SqlConnection?

时间:2014-10-03 13:07:25

标签: c# .net sqlconnection ormlite-servicestack

我正在尝试将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总是空的,有什么想法吗?

1 个答案:

答案 0 :(得分:4)

因为连接包装在托管OrmLiteConnectionWrapper中,所以可以使用以下命令获取SqlConnection:

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