gpt4 book ai didi

c# - EF6 - 有没有办法在不对数据库造成任何更改的情况下清除 EF 缓存/本地项目?

转载 作者:太空狗 更新时间:2023-10-29 20:20:29 32 4
gpt4 key购买 nike

基本上,我将 EF 与对执行一些批量删除的存储过程的一次调用混合在一起,否则 EF 太慢。

下面是这个场景的一些伪代码(我在现实中有更复杂的代码):

public void RemoveCustomer(int customerUID)
{
// this code is running in one db transaction
{
// retrieve certain orders of particular customer using EF
var orders = repoOrders.GetOrdersOfCustomer(filter, customerUID);

// do something with above orders before deletion using EF
repoX.DoSomethingWithOrders(orders);

// call SP to delete all orders of customer
repoOrders.DeleteAllOrdersOfCustomer(customerUID); // this calls a stored procedure

// delete customer using EF
repoCustomers.DeleteCustomer(customerUID); // throws exception due to relationship!
}
}

当然,客户订单是one-to-many (1:m) 关系。

我想避免在上面的场景中,当属于被删除的客户的上下文加载了一些订单时抛出的异常。异常(exception)是:

"The relationship could not be changed because one or more of the foreign-key properties is non-nullable. When a change is made to a relationship, the related foreign-key property is set to a null value. If the foreign-key does not support null values, a new relationship must be defined, the foreign-key property must be assigned another non-null value, or the unrelated object must be deleted."

所以,我想知道是否可以清除来自 <DbSet>.Local 的部分/所有订单在调用存储过程之后和删除用户之前不会对数据库造成任何更改。

我猜 Detach可以使用,但这意味着我应该循环遍历。

你会推荐什么?

编辑: 我是 EF 的新手,在使用 ADO.NET 完成存储库后,我现在正在集成 EF,是的,BL 一直保持不变......所以我试试这个在这一点上以最小的努力集成。

注意:我无法更改数据库结构。

最佳答案

我个人会让每个存储库方法使用自己的上下文,在方法末尾保存自己的更改等,然后使用 TransactionScope 来确保操作是原子的。

void DeleteAllOrdersOfCustomer(Guid customerUID)
{
using (var context = new Context())
{
...
context.SaveChanges();
}
}

...

using (var ts = new TransactionScope())
{
// call SP to delete all orders of customer
repoOrders.DeleteAllOrdersOfCustomer(customerUID); // this calls a stored procedure

// delete customer using EF
repoCustomers.DeleteCustomer(customerUID); // throws exception due to relationship!
ts.Complete();
}

关于c# - EF6 - 有没有办法在不对数据库造成任何更改的情况下清除 EF 缓存/本地项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24085175/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com