简体   繁体   English

实体框架6数据库优先-如何与ADO共享连接和事务

[英]Entity Framework 6 Database First - How to share connection and transaction with ADO

Is it possible to share one connection (and transaction as well) between operations made in EF6 DB First approach and some ADO operations? 是否可以在EF6 DB First方法中进行的操作与某些ADO操作之间共享一个连接(以及事务)?

As I read here: https://msdn.microsoft.com/en-us/data/dn456843.aspx#existing it is possible to share connection and transactions since EF v6, but I have to pass SqlConnection object as a parameter to the constructor of context class. 正如我在这里阅读的那样: https : //msdn.microsoft.com/zh-cn/data/dn456843.aspx#existing自EF v6起可以共享连接和事务,但是我必须将SqlConnection对象作为参数传递给上下文类的构造函数。 But if I do that in DB First approach , I've got UnintentionalCodeFirstException. 但是,如果我使用DB First方法执行此操作,则会遇到UnintentionalCodeFirstException。

As I read here: https://msdn.microsoft.com/en-us/data/jj592674 I have to use instance of EntityConnection as a parameter to the constructor of context class when DB First approach is used. 正如我在此处阅读的那样: https ://msdn.microsoft.com/zh-cn/data/jj592674当使用DB First方法时,我必须使用EntityConnection实例作为上下文类的构造函数的参数。 But EntityConnection class constructor accept only CLOSED connections. 但是EntityConnection类构造函数仅接受CLOSED连接。 And therefore I cannot share transaction, because connection has to be closed before passed to context class. 因此,我无法共享事务,因为在传递给上下文类之前必须关闭连接。

Am I right and it is impossible to share one connection in this scenario, or maybe there is some other way? 我是对的,在这种情况下不可能共享一个连接,或者还有其他方法吗?

Is TransactionScope still the only way to wrap operations in EF 6 DB First and ADO in a transaction (with separate connections) ? TransactionScope仍然是在事务(具有独立连接)中将EF 6 DB First和ADO中的操作包装起来的唯一方法吗?

I can not remember where I did get this from, but it helped me with running EF and SqlBulkCopy in same transaction. 我不记得我从哪里得到的,但是它帮助我在同一事务中运行EFSqlBulkCopy Here is how to grab transaction with reflection from Entity Framework : 这是通过Entity Framework进行反射来获取事务的方法:

EntityConnection ec = (EntityConnection)Context.Connection;
SqlConnection sc = (SqlConnection)ec.StoreConnection;
SqlTransaction sqlTransaction = null;

var parserProp = sc.GetType().GetProperty("Parser", BindingFlags.NonPublic | BindingFlags.Instance);

if (parserProp != null)
{
    var parser = parserProp.GetValue(sc, null);
    var sqltxProp = parser.GetType().GetProperty("CurrentTransaction", BindingFlags.NonPublic | BindingFlags.Instance);
    var currentTransaction = sqltxProp.GetValue(parser, null);
    sqlTransaction = currentTransaction as SqlTransaction;

    if (sqlTransaction == null)
    {
        var parentProp = currentTransaction.GetType().GetProperty("Parent", BindingFlags.NonPublic | BindingFlags.Instance);
        currentTransaction = parentProp.GetValue(currentTransaction, null);
        sqlTransaction = currentTransaction as SqlTransaction;
    }
}

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

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