由于主键,无法删除表中的行

时间:2018-12-25 12:52:00

标签: sql-server asp.net-mvc

我无法使用自动递增且在多个表上具有IDENTITY的主键删除行。我已经建立了多对多关系表。我是新手,不确定如何进行必要的修改。

CREATE TABLE [dbo].[Activity] 
(
    [Activity_Id] INT IDENTITY (1, 1) NOT NULL,
    [Action_Id]   INT NOT NULL,
    [Actuator_Id] INT NOT NULL,
    [Duration]    INT NULL,
    [Amount]      INT NULL,

    PRIMARY KEY CLUSTERED ([Activity_Id] ASC),

    CONSTRAINT [fk1] 
        FOREIGN KEY ([Action_Id]) REFERENCES [dbo].[Action] ([Action_Id]) 
                ON DELETE CASCADE ON UPDATE CASCADE,
    CONSTRAINT [fk2] 
        FOREIGN KEY ([Actuator_Id]) REFERENCES [dbo].[Actuator] ([Actuator_Id]) 
                ON DELETE CASCADE ON UPDATE CASCADE
);

CREATE TABLE [dbo].[Action] 
(
    [Action_Id] INT          IDENTITY (1, 1) NOT NULL,
    [Name]      VARCHAR (45) NOT NULL,

    PRIMARY KEY CLUSTERED ([Action_Id] ASC)
);

CREATE TABLE [dbo].[Actuator] 
(
    [Actuator_Id]  INT          IDENTITY (1, 1) NOT NULL,
    [ActuatorName] VARCHAR (45) NOT NULL,
    [Status]       TINYINT      DEFAULT ((0)) NOT NULL,
    [ip]           VARCHAR (30) NULL,

    PRIMARY KEY CLUSTERED ([Actuator_Id] ASC)
);

我尝试使用名称删除动作,但名称不是唯一的。

// Controller 
public IActionResult ActionDelete(string Action_Id, string Actuator_Id)
{
    string sql = "SELECT * FROM dbo.Action INNER JOIN dbo.Activity ON dbo.Activity.Action_Id = dbo.Action.Action_Id INNER JOIN dbo.Actuator ON dbo.Activity.Actuator_Id = dbo.Actuator.Actuator_Id WHERE dbo.Action.Action_Id = {0} AND dbo.Activity.Actuator_Id ={0} ; ";
    string select = String.Format(sql, Action_Id,Actuator_Id);

    DataTable dt = DBUtl.GetTable(select);

    if (dt.Rows.Count != 1)
    {
        TempData["Message"] = "Action does not exist";
        TempData["MsgType"] = "warning";
    }
    else
    {
        sql = "DELETE FROM dbo.Action WHERE Action_Id={0}; DELETE FROM dbo.Actuator WHERE Actuator_Id={0}";
        string delete = String.Format(sql, Action_Id, Actuator_Id);
        int res = DBUtl.ExecSQL(delete);

        if (res == 1)
        {
            TempData["Message"] = "Action Deleted";
            TempData["MsgType"] = "success";
            return RedirectToAction("Actions");
        }
        else
        {
            TempData["Message"] = DBUtl.DB_Message;
            TempData["MsgType"] = "danger";
        }
    }

    return RedirectToAction("Actions");
}

我希望该行被action_id和actuator_id删除,但是if (dt.Rows.Count != 1)的引用引用为空。

0 个答案:

没有答案