是否有可能在EF中获得现有的DbContext?

时间:2016-02-23 21:45:03

标签: c# entity-framework design-patterns

我需要从数据层抽象事务。 在业务层我想做:

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

在数据层中:

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

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

    public void Rollback()
    { 
    }

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

对于旧方法(TransactionScope),ITransaction的实现应该是这样的:

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

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

    //implementation of interface
}

现在建议使用Database.BeginTransaction()来启动事务。可能ITransaction的实施应该是:

    let pamTuples = [  
        (UIImage(named: "1_1")!, "1"),  
        (UIImage(named: "1_2")!, "2"),  
        (UIImage(named: "1_3")!, "3"),  
        (UIImage(named: "1_4")!, "4"),  
        (UIImage(named: "2_1")!, "5"),  
        (UIImage(named: "2_2")!, "6"),
        (UIImage(named: "2_3")!, "7"),
        (UIImage(named: "2_4")!, "8"),
        (UIImage(named: "3_1")!, "9"),
        (UIImage(named: "3_2")!, "10"),
        (UIImage(named: "3_3")!, "11"),
        (UIImage(named: "3_4")!, "12"),
        (UIImage(named: "4_1")!, "13"),
        (UIImage(named: "4_2")!, "14"),
        (UIImage(named: "4_3")!, "15"),
        (UIImage(named: "4_4")!, "16")    
    ]  

    let imageChoices : [ORKImageChoice] = pamTuples.map {  
        return ORKImageChoice(normalImage: $0.0, selectedImage: nil, text: $0.1, value: $0.1)  
    }  

    let pamAnswerFormat: ORKImageChoiceAnswerFormat = ORKAnswerFormat.choiceAnswerFormatWithImageChoices(imageChoices)  

    let pamQuestionStep = ORKQuestionStep(identifier: "mood image", title: pamQuestionStepTitle, answer: pamAnswerFormat)  

如何将DbContext实例从事务转移到EFDBModification对象?我考虑将上下文的实现作为线程或webrequest的单例,但不确定这一点。或以其他方式获取现有的DbContext。我不想将它作为参数传递给Modify()方法。

0 个答案:

没有答案