简体   繁体   English

实体框架6在数据库级别处理事务

[英]Entity Framework 6 Handle Transaction At Database Level

I have a stored procedure that uses transactions at a database level (the transactions are handled within the stored procedure itself). 我有一个在数据库级别使用事务的存储过程(事务在存储过程本身内处理)。 This means I need to tell Entity Framework not to handle transactions. 这意味着我需要告诉实体框架不要处理事务。

Now using database first model I can import the stored procedure and have an auto generated context class that looks like the following: 现在,使用数据库优先模型,我可以导入存储过程,并具有一个自动生成的上下文类,如下所示:

 public virtual int MyStoredProcedure()
 {         
    return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction("MyStoreProcedure");
 }

I can add my own method to the DbContext class that looks like the following: 我可以将自己的方法添加到DbContext类中,如下所示:

public virtual int MyStoredProcedureWithoutTransaction()
{
    this.Database.ExecuteSqlCommand(TransactionalBehavior.DoNotEnsureTransaction, "MyStoredProcedure")
}

My question is does the following code also behave the same as the MyStoredProcedureWithoutTransaction() in terms of transaction management: 我的问题是,以下代码在事务管理方面是否也与MyStoredProcedureWithoutTransaction()相同:

MyContext context = new MyContext();
context.Database.UseTransaction(null);
context.MyStoredProcedure();

If it does I would prefer to use the second version as it will have the advantage of using the auto generated code from Entity Framework. 如果可以,我宁愿使用第二个版本,因为它具有使用Entity Framework自动生成的代码的优势。

If anyone comes across this post and is wondering the answer is No! 如果有人遇到这篇文章,并想知道答案是否定的!

context.Database.UseTransaction(null);

Is not the same as using TransactionalBehavior.DoNotEnsureTransaction on the ExecuteSqlCommand overloaded method. 与在ExecuteSqlCommand重载方法上使用TransactionalBehavior.DoNotEnsureTransaction

However the following does work and can be used how I originally wanted: 但是以下内容确实可以工作,并且可以按我最初的意愿使用:

((IObjectContextAdapter)_context).ObjectContext.ContextOptions.EnsureTransactionsForFunctionsAndCommands = false;

In the application I simply created a base repository class as follows: 在应用程序中,我仅创建了一个基础存储库类,如下所示:

public abstract class BaseEntityFrameworkNonTransactionRepository<T> where T : DbContext, new()
{
    protected T _context;

    protected BaseEntityFrameworkNonTransactionRepository()
    {
        _context = new T();
        ((IObjectContextAdapter)_context).ObjectContext.ContextOptions.EnsureTransactionsForFunctionsAndCommands = false;
    }
}

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

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