“EntityConnection 只能用封闭的 DbConnection 构造”这是我在尝试构造提供开放连接的 entityconnection 时遇到的问题。有一个事务范围打开,我不想打开新连接,否则事务将被提升为 dtc 事务,因为我的理解是,如果我在多个 entityConnections 上使用单个 SqlConnection,我不需要 DTC。
所以,我的代码大致是这样的。
提前致谢...
using (TransactionScope transactionScope = new TransactionScope())
{
using (SqlConnection dwConn = GetDWConnection(user))
{
dwConn.Open();
// I need to do some SQlConnection specific actions first
//EntityConnection specific actions next
Func1(dwConn);
Func2(dwConn); //similar to Func1()
Func3(dwConn); //Similar to Func1()
}
}
Func1(SqlConnection dwConn)
{
using (EntityConnection conn = GetSQLEntityConnection(sqlConnection))
{
ObjectContext objectContext = (ObjectContext)Activator.CreateInstance(objectContextType, new object[] { conn });
//few actions
}
}
private EntityConnection GetSQLEntityConnection(SqlConnection sqlConnection)
{
//few steps
EntityConnection entityConnection = new EntityConnection(entityConnectionStringBuilder.ToString());
EntityConnection sqlEntityConnection = new EntityConnection(entityConnection.GetMetadataWorkspace(),sqlConnection);
return sqlEntityConnection;
}