0

我有一个情况,我有 2 个数据库。

经理有公司表,基于这个值我必须创建一个新的数据库。

所以我正在使用 TransactionScope。我想知道以下是否正确?

这会回滚这两个变化吗?如果发生错误,在两个数据库中?

using (TransactionScope ts = new TransactionScope())
{
    try
    {
        using(var ManagerContext = new ManagerEntities(
            ConnectionStringManager.GetManagerConnectionString()))
        {
            //Operations on Manager DB                         
            // Create new Company and get NEWCOMPANYID 
            // -- Used to create new DB
        }

        using(var companyContext = new CompanyEntities(
            ConnectionStringManager.GetCompanyConnectionString(
                NEWCOMPANYID.ToString())))
        {
            //Create New Company DB
        }

        ts.Complete();
    }
    catch (Exception ex)
    {
        ts.Dispose();
    }
}
4

2 回答 2

2

As long as both those database contexts are TransactionScope aware, and don't explicitly have ambient transaction enlisting disabled (in the connection string, for example), then yes: that should work fine. If we assume that the two connection strings are different, this will definitely require a distributed transaction (DTC), though - whether that is OK is up to you. If the connection strings are identical, you might get away with the LTM instead (less overhead / configuration).

Note that as per the comments - you don't need the try/finally.

于 2013-09-09T08:11:50.283 回答
2

这没关系,尽管它会触发 DTC,正如 Marc 所解释的那样。您可以通过使用两个上下文共享的单个SqlConnection(或)来避免 DTC。EntityConnection您可以使用 切换连接的当前数据库ChangeDatabase。这避免了对分布式事务的需要。

您还需要显式打开连接,因为默认情况下 EF 会为每个操作打开并关闭它。这会导致多个 DTC 登记(超过 2 个)。这是 EF 的设计缺陷。

于 2013-09-09T10:44:53.837 回答