我需要从两个表中删除一条记录(Asp.netUser表 - 包含所有注册详细信息和检查帐户表 - 保存所有用户详细信息)。删除操作方法仅允许在检查Accounts表上执行删除操作。我应该写什么查询/代码来删除所有表中的记录?
删除操作方法
public ActionResult Delete(int? id)
{
if (id == null)
return HttpNotFound();
var del = db.checkAccounuts.Find(id);
if (del == null)
return HttpNotFound();
db.checkAccounuts.Remove(del);
db.SaveChanges();
return RedirectToAction("ViewAccounts");
}
可以从此表中删除记录
CREATE TABLE [dbo].[CheckingAccount] (
[Id] INT IDENTITY (1, 1) NOT NULL,
[AccountNumber] VARCHAR (10) NOT NULL,
[FirstName] NVARCHAR (MAX) NOT NULL,
[LastName] NVARCHAR (MAX) NOT NULL,
[Balance] DECIMAL (18, 2) NOT NULL,
[AppUserId] NVARCHAR (MAX) NOT NULL,
[User_Id] NVARCHAR (128) NULL,
CONSTRAINT [PK_dbo.CheckingAccounts] PRIMARY KEY CLUSTERED ([Id] ASC),
CONSTRAINT [FK_dbo.CheckingAccounts_dbo.AspNetUsers_User_Id] FOREIGN KEY ([User_Id]) REFERENCES [dbo].[AspNetUsers] ([Id])
);
但用户详细信息仍保留在此表中!
CREATE TABLE [dbo].[AspNetUsers] (
[Id] NVARCHAR (128) NOT NULL,
[Email] NVARCHAR (256) NULL,
[EmailConfirmed] BIT NOT NULL,
[PasswordHash] NVARCHAR (MAX) NULL,
[SecurityStamp] NVARCHAR (MAX) NULL,
[PhoneNumber] NVARCHAR (MAX) NULL,
[PhoneNumberConfirmed] BIT NOT NULL,
[TwoFactorEnabled] BIT NOT NULL,
[LockoutEndDateUtc] DATETIME NULL,
[LockoutEnabled] BIT NOT NULL,
[AccessFailedCount] INT NOT NULL,
[UserName] NVARCHAR (256) NOT NULL,
[Pin] NVARCHAR (MAX) NULL,
CONSTRAINT [PK_dbo.AspNetUsers] PRIMARY KEY CLUSTERED ([Id] ASC)
);
GO
CREATE UNIQUE NONCLUSTERED INDEX [UserNameIndex]
ON [dbo].[AspNetUsers]([UserName] ASC);
任何帮助将不胜感激!
答案 0 :(得分:0)
您必须通过检查帐户对象找到用户详细信息然后将其删除,修改后的方法将如下所示
public ActionResult Delete(int? id)
{
if (id == null)
return HttpNotFound();
var del = db.checkAccounuts.Find(id);
if (del == null)
return HttpNotFound();
aspnetusers user = db.aspnetusers.find(del.User_Id);
db.checkAccounuts.Remove(del);
db.aspnetusers.remove(user.ID);
db.SaveChanges();
return RedirectToAction("ViewAccounts");
}
如果要从后端执行删除,可以使用SQL表触发器删除用户表中的数据,方法是删除检查表中的记录,或者也可以使用存储过程从两个表中删除记录,只需调用代码中的存储过程。