【发布时间】:2016-03-16 10:50:40
【问题描述】:
将 DbContext 传递给另一个方法的问题,例如:
public bool MarkCustomerForDelete(Customer customerObj)
{
using(var dbContext = new MyContext())
{
using(var dbTransaction = dbContext.Database.BeginTransaction())
{
//Clear all orders for the Given Customers
var orderList = dbContext.Orders.Where(x=>x.id == customerObj.OrderId).ToList();
CommonLogicMethod(dbContext, orderList);
//Logic
customerObj.Status = "Deleted";
// The Modification will fail over due to the Customer Object for that object is already attached to the DbContext with Previous Values
dbContext.Entry(customerObj).State = EntityState.Modified;
dbContext.SaveChanges();
dbTransaction.Commit()
return true;
}
}
}
public void DeleteOrderRelatedData(MyContext dbContext, List<Orders> orderList)
{
foreach(var entity2 in entity2List)
{
var OrderAddresses = dbContext.OrderAddresses.Where(x=>x.Id == entity2.Id).ToList();
//Now if here the dbContext has 100 Entities (Tables)
//It internally Enumerates all the entities in the Local cache i.e. dbContext.Coupons.Local has all the Records from the DB in the Local present.
}
}
问题:为什么当 DbContext 被传递给另一个方法时,内部调用了所有数据,即 dbContext.Customers.Local 中的所有数据都在一级缓存中?
问题:如何将 DbContext 从一种方法传递到另一种方法(不创建上述问题)?
这是创建与修改数据相关的问题,即 DeleteCustomer 将故障转移。 现在,如果将 DeleteOrderRelatedData 中的代码合并到 DeleteCustomer 函数中,它就可以正常工作了。
我为 dbContext 添加了一个日志,而 dbContext 在内部将其传递给函数时正在调用与不同查询相关的所有 Select 查询..
欲了解更多详情,请观看此视频:Link
正在使用的工具:
- 实体框架 6.0
- System.Data.Sqlite
- 用于 MethodBoundary Aspect 的 PostSharp。
【问题讨论】:
-
正如@wardy 所说,上下文不会自发加载数据。当它被传递给一个方法时,它不会突然获取数据。如果您检查,您会看到它在 传递它之前获得了所有数据。也许你应该在调试进程的同时监控执行的 SQL。
-
@GertArnold:请查看视频screencast.com/t/1csUc22eA4Jk。它说明了问题。
-
不敢相信。但是您确定它不是调试器工件吗?只是运行程序时也会发生这种情况吗?
Customer下方的波浪线说明了什么? -
@GertArnold :它只是通过将 DbContext 传递给另一个函数而发生的。检查我给出的答案;这实际上造成了问题。
标签: c# entity-framework sqlite entity-framework-6 system.data.sqlite