在我的Web Api应用程序中,我有一些这样的表格,在创建process
并上传文件时,一些信息已添加到tableLogs
:
tableProcess
-------------------
ProcessId Name
1 proc1
2 proc2
tableFile
------------------------------
FileId ProcessId Name
1 1 file1
2 1 file2
3 1 file3
4 2 file4
5 2 file5
tableLogs
------------------
LogId FileId Description
1 1 log1
2 1 log2
3 2 log3
4 2 log4
5 3 log5
6 4 log6
7 5 log7
我需要从所有这些表中删除process
删除记录,例如,如果我要删除proc1
,文件file1
,file2
和&应从file3
中删除tableFile
,并且应从tableLogs
中删除与这三个文件匹配的前五个日志。我没有删除与tableFile
相关的日志。有任何建议怎么做?
更新
我创建了一个商店程序,正如@ websch01ar在他的回答中所建议的那样,现在我的方法看起来像这样:
public IHttpActionResult DeleteLeadProcess(int id)
{
var procId = db.tableProcess.SingleOrDefault(p => p.ProcessId == id);
string errMsg = null;
using (var transaction = db.Database.BeginTransaction())
{
try
{
db.deleteProcess(id);
transaction.Commit(); <-- error here
}
catch (Exception e)
{
transaction.Rollback();
errMsg = e.Message;
return BadRequest(errMsg);
}
}
return Ok("Process " + procId.ProcessName + " has been deleted successfully!");
}
如果我在SQL Server中运行它,该过程可以正常工作,但在控制器中我有一个错误&#34;抛出了System.Data.SqlClient.SqlException:&#34;无法执行事务操作,因为有处理此交易的待处理请求。&#34;
答案 0 :(得分:0)
我建议您在需要处理级联删除时切换到执行存储过程。这是您可能使用的人为存储过程。请注意,我使用自己的sproc模板,你可能不需要所有这些
USE [Database]
GO
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[csp_Application_DeleteProcessRecords]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[csp_Application_DeleteProcessRecords]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[csp_Application_DeleteProcessRecords]
@ProcessID int
AS
BEGIN
/******************************************************************************
** File: csp_Application_DeleteProcessRecords.sql
** Name: csp_Application_DeleteProcessRecords
** Desc:
*******************************************************************************
** Change History
*******************************************************************************
** Date: Author: Description:
** -------- -------- -------------------------------------------
** 07-31-00 Cool Developer Creation.
**
*******************************************************************************/
BEGIN TRY
/*
Delete from tableLogs
*/
Delete TL
from [Database].dbo.tableLogs TL
JOIN [Database].dbo.tableFile TF on TL.FileID = TF.FileID
Where TF.ProcessID = @ProcessID;
/*
Delete from tableFile
*/
Delete TF
from [Database].dbo.tableFile TF
Where TF.ProcessID = @ProcessID;
/*
Delete from Process
*/
Delete TP
from [Database].dbo.tableProcess TP
where ProcessID = @ProcessID;
Select 1; -- true as an output?
END TRY
BEGIN CATCH
BEGIN
Rollback;
DECLARE @ErrorMessage NVARCHAR(4000), @ErrorSeverity INT, @ErrorState INT;
SELECT
@ErrorMessage = ERROR_MESSAGE(),
@ErrorSeverity = ERROR_SEVERITY(),
@ErrorState = ERROR_STATE();
RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);
END
END CATCH;
END
Go
/*
** Test Scripts
*/
/*
Declare @ProcessID int = (Select 'A')
exec [Database].dbo.csp_Application_DeleteProcessRecords @ProcessID 1
*/