gpt4 book ai didi

c# - 事务未在 Entity Framework 中提交

转载 作者:太空宇宙 更新时间:2023-11-03 15:17:48 25 4
gpt4 key购买 nike

尝试使用 Entity Framework 执行复杂的过程并将数据保存在事务中的表中。当我的代码提交事务时,它会抛出异常

无法执行交易操作,因为有待处理的请求处理此交易。

下面是代码。

using (abcEntities dbContext = new abcEntities())
{
using (var transaction = dbContext.Database.BeginTransaction())
{
dbContext.USP_ResellerCustomerFile_DeleteFiles(customerId, fileId, 1);
ResellerAndCustomerActivityDAL objCustomerActivityDAL = new ResellerAndCustomerActivityDAL();

ResellerAndCustomerActivity objActivity = new ResellerAndCustomerActivity()
{
Activity = objfile.FileName + " is temporairly permanently deleted.",//message.ReplacingSpecialCharacterswithEntities(),
ActivityDate = DateTime.UtcNow,
ResellerAndCustomerId = customerId,
UserTypeId = 2

};

dbContext.ResellerAndCustomerActivities.Add(objActivity);

//objCustomerActivityDAL.Create(objfile.FileName + " is permanently deleted.", objUnit, out returnMessage, customerId);

dbContext.SaveChanges();
transaction.Commit();
}
}

不知道为什么它会抛出挂起的请求异常,因为我在同一个事务中执行它。

下面是完整的堆栈跟踪

   at System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch[TTarget,TInterceptionContext](TTarget target, Action`2 operation, TInterceptionContext interceptionContext, Action`3 executing, Action`3 executed)
at System.Data.Entity.Infrastructure.Interception.DbTransactionDispatcher.Commit(DbTransaction transaction, DbInterceptionContext interceptionContext)
at System.Data.Entity.Core.EntityClient.EntityTransaction.Commit()
at System.Data.Entity.DbContextTransaction.Commit()
at BoomerangResellerAPI.DAL.ResellerCustomerFileDAL.DeleteFile(Int32 customerId, Int32 fileId, String& returnMessage) in D:\Varinder\Working Folder\Boomerang Backup\API\BoomerangResellerAPI\BoomerangResellerAPI\BoomerangResellerAPI.DAL\ResellerCustomerFileDAL.cs:line 325
at BoomerangResellerAPI.BLL.ResellerCustomerFileBLL.DeleteFile(Guid uniqueCustomerId, Int32 fileId, String& returnMessage) in D:\Varinder\Working Folder\Boomerang Backup\API\BoomerangResellerAPI\BoomerangResellerAPI\BoomerangResellerAPI.BLL\ResellerCustomerFileBLL.cs:line 100
at BoomerangResellerAPI.Controllers.FilesController.TemporaryDelete(Nullable`1 customerUniqueId, Nullable`1 fileId) in D:\Varinder\Working Folder\Boomerang Backup\API\BoomerangResellerAPI\BoomerangResellerAPI\BoomerangResellerAPI\Controllers\FilesController.cs:line 195

最佳答案

我找到了另一种方法。

与其直接从 dbcontext 调用存储过程,不如直接调用它dbContext.Database.DbRawSqlQuery。现在我正在按照以下顺序执行上述所有操作

  1. 声明和初始化 dbcontext。
  2. 创建交易。
  3. 使用步骤 1 中初始化的上下文执行过程。
  4. 使用相同的 ddContex 在数据库中保存记录。
  5. 将更改从 dbContext 保存到数据库。
  6. 提交交易。

甚至不需要创建事务,因为所有实体(与数据库相关)的语句默认都在事务中执行。可以读作here

关于c# - 事务未在 Entity Framework 中提交,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38372770/

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