1

I am not sure the best way to handle the DbContext when one method "needs" 2 DbContext objects. I have classes that do the normal CRUD operations, and after each insert/edit, I log the changes that were made -using Log_History entity. Rather than duplicating the same code in multiple classes, I created a public static method for adding a new Log_History entity.

My initial thought was this can't be a good idea. Would there be a concurrency issue using 2 DbContext objects? I am not sure if I understood correctly, but this question got the response that multiple contexts are okay. What about passing my DbContext in CreateOrder() as an argument of AddHistoryNote(); would that be an acceptable approach?

public class Log
{

public static void AddHistoryNote(Guid UserId, string Type, string Detail)
{
    using (rsContext repo = new rsContext()) {
        Log_History trans = new Log_History {
            UserId = UserId,
            Description = Type,
            Detail = Detail,
            HistoryDate = DateTime.Now
        };

        repo.Log_History.Add(trans);
        repo.SaveChanges();
    }

}

}

public class DoStuff
{

private void CreateOrder(BT.TransactionInfo TransDetails)
{
    using (rsContext repo = new rsContext()) {
        rsDataAccess.Order newOrder = new rsDataAccess.Order {
            Amount = TransDetails.Amount,
            OrderDate = DateTime.Now,
            Status = Status.RIDER_PAID,
            RequestId = TransDetails.RequestId
        };

        ' Add hisotry here 
        Log.AddHistoryNote(TransDetails.UserId, "TransactionType", "My history note");

        repo.Orders.Add(newOrder);
        repo.SaveChanges();
    }
 }
}
Community
  • 1
  • 1
KRob
  • 389
  • 3
  • 19
  • 1
    Can't you just pass the DBContext in as a parameter and use it from there? – Jane S Aug 01 '14 at 04:36
  • 1
    That is what I meant by "passing the DbContext in CreateOrder() as an argument of AddHistoryNote()." I know it would work, but I needed some assurance that it would be an effective approach. – KRob Aug 01 '14 at 04:39
  • 1
    Sorry :) Yes, in that case I can't see there being an issue. It also allows you to manage the transaction anyway. – Jane S Aug 01 '14 at 04:40

1 Answers1

0

I'm not sure what you think is a problem here, but nothing is.

There are no concurrency issues with calling a static method like this. Your DbContext itself is not static (if it was, that would be a problem) and you are newing up a new instance.

That's not to say I would recommend doing this, but it's not going to be an error.

Erik Funkenbusch
  • 92,674
  • 28
  • 195
  • 291
  • What would you recommend, or why would you not recommend this? – KRob Aug 01 '14 at 05:25
  • 1
    @KRob - I wouldn't recommend it because it's unnecessary. I would probably implement it as a C# extension method on the DbContext, or a method of the DbContext. – Erik Funkenbusch Aug 01 '14 at 05:40