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();
}
}
}