【发布时间】:2014-09-24 05:25:41
【问题描述】:
当一种方法“需要”2 DbContext 对象时,我不确定处理DbContext 的最佳方法。我有执行正常 CRUD 操作的类,并且在每次插入/编辑之后,我记录所做的更改 - 使用 Log_History 实体。我没有在多个类中复制相同的代码,而是创建了一个公共静态方法来添加一个新的Log_History 实体。
我最初的想法是这不是一个好主意。使用 2 个DbContext 对象会不会出现并发问题?我不确定我是否理解正确,但this question 得到的响应是多个上下文都可以。将CreateOrder() 中的DbContext 作为AddHistoryNote() 的参数传递怎么样?这是一种可以接受的方法吗?
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();
}
}
}
【问题讨论】:
-
你不能只将 DBContext 作为参数传入并从那里使用它吗?
-
这就是我所说的“将 CreateOrder() 中的 DbContext 作为 AddHistoryNote() 的参数传递”的意思。我知道它会起作用,但我需要一些保证,这将是一种有效的方法。
-
对不起 :) 是的,在这种情况下,我看不出有问题。它还允许您管理交易。
标签: c# asp.net entity-framework entity-framework-4 dbcontext