简体   繁体   English

实体框架6多个数据上下文共享事务

[英]Entity Framework 6 Multiple Datacontext Sharing a transaction

using(var Db = new Framework_DbContext())
{
    var DbContextTransaction = Db.Database.BeginTransaction(IsolationLevel.ReadUncommitted);
    using (var db = new DocumentLibDbContext())
    {
        //**How to use the above DbContextTransaction??**
        db.Database.UseTransaction(DbContextTransaction.UnderlyingTransaction);
    }
}

You didn't specify whether your contexts connect to the same database or not. 您没有指定上下文是否连接到同一数据库。

If the databases are different, you need to avoid BeginTransaction and UseTransaction and instread wrap your code in a TransactionScope . 如果数据库不同,则需要避免BeginTransactionUseTransaction并将代码instread封装在TransactionScope

Assuming they both connect to the same database, you don't specify whether you are using an EDMX or Code First. 假设它们都连接到同一数据库,则无需指定使用的是EDMX还是Code First。 I had the same problem using EDMX, spent the whole day with trial and error and finally came up with a solution. 我在使用EDMX时遇到了同样的问题,花了一整天的时间反复尝试,最后提出了解决方案。

var workspace = new MetadataWorkspace(new[] { "res://*/" }, new[] { Assembly.GetExecutingAssembly() });
using (var connection = new SqlConnection("data source=.;initial catalog=MultpleEdmxTest;integrated security=True;MultipleActiveResultSets=True"))
{
    using (var entityConnection1 = new EntityConnection(workspace, connection, false))
    {
        using (var entityConnection2 = new EntityConnection(workspace, connection, false))
        {
            connection.Open();
            using (var transaction = connection.BeginTransaction())
            {
                using (var schema1Entities = new Schema1Entities(entityConnection1))
                {
                    schema1Entities.Database.UseTransaction(transaction);
                    // code goes here
                    schema1Entities.SaveChanges();
                }

                using (var schema2Entities = new Schema2Entities(entityConnection2))
                {
                    schema2Entities.Database.UseTransaction(transaction);
                    // code goes here
                    schema2Entities.SaveChanges();
                }
                transaction.Commit();
            }
        }
    }
}

You define the extra constructors in partial classes like so: 您可以在部分类中定义额外的构造函数,如下所示:

partial class Schema1Entities
{
    public Schema1Entities(DbConnection connection) : base(connection, false) { }
}

where false indicates that you open and close the connection manually. 其中false表示您手动打开和关闭连接。

As a bonus you now only need one connection string in your config and it doesn't include all the useless EF junk that normally comes with it (metadata=res://*/blabla). 另外,您现在只需在配置中使用一个连接字符串即可,它不包括通常随附的所有无用的EF垃圾(metadata = res:// * / blabla)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM