0

I have a method that uses an EF 6 data model and is wrapped within a using statement. There are some additional and common steps that need to be done where Id rather not include them all in one method. The code below, while not the exact code Im using, seems to work. However, Im wondering if there is any "gotchyas" Im setting up related to EF-specific issues dealing with the DbContext itself. Especially in how everything must be translated to SQL?

The main goal is to do several operations on several entities before calling SaveChanges so that the implicit transactions covers all the changes rather than calling SaveChanges more than once leaving the option open for orphaned changes.

AppendFlagToOrder(ref DbContext tx, ref CustOrder o) {
    var oSettings = (from a in tx.OrderSettings where a.Type == o.OrderType select a).FirstOrDefault();
    if(!oSettings == null) {
        o.IsFlagged = oSettings.Flagged
    }
}


CheckOrderFlag(int OrderId) {       

     using (var ctx = new StoreDbCtx()) {
        CustOrder co = (from a in ctx.Orders where a.Id == OrderId select a).FirstOrDefault();
        AppendFlagToOrder(ctx,co);

        //-- continue with other operations
    }   
}

1 Answer 1

1

You normally don't want to pass DbContext around like that as anyone would have the ability to call SaveChanges() on you at any point. The easiest thing to do would be to create an IStoreDbCtx interface that only has the DbSets on it you want exposed. Then you send that type through to the sub methods so they can't access SaveChanges() on you.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.