mardi 23 février 2016

Is it possible to get an existing DbContext in EF?

I need to abstract transaction from data layer. In business layer I want to do:

IModify modification = modification.Get();
using (ITransaction transaction = Transaction.Get())
{
    try
    {
        modification.Modify(); //do some changes
        transaction.Commit();  
    }
    catch 
    {
        transaction.Rollback();
    }
}

In data-layer:

public class EFDBModification : IModify
{
     public void Modify()
     { 
         using(var context = new MyDbContext())
         {
             // work with entities
             context.SaveChanges();
         }
     }
}

For old approach (TransactionScope) maybe implementation of ITransaction should be like this:

public class EFTransaction : ITransaction
{
    private TransactionScope _scope = new TransactionScope();

    public void Commit()
    { 
        _scope.Complete();
    }

    public void Rollback()
    { 
    }

    public Dispose()
    {
        _scope.Dispose();
    }
}

Now it is recommended to use Database.BeginTransaction() to start the transaction. Probably ITransaction implementation should be:

public class EFTransaction : ITransaction
{ 
    private MyDbContext _context = new MyDbContext();
    private Transaction _transactionContext;    

    public EFTransaction()
    {
        _transactionContext = _context.Database.BeginTransaction();
    }

    //implementation of interface
}

How should I transfer DbContext instance from transaction to EFDBModification object? I thought about the implementation of context as a singleton for a thread or for a webrequest but not sure about this. Or in some other way get existing DbContext. I dont want to pass it as argument to Modify() method.

Aucun commentaire:

Enregistrer un commentaire