gpt4 book ai didi

c# - DELETE 语句冲突(ASP.NET MVC)

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

我有 ASP.NET MVC 应用

我有两个相关表 Companies 和 Vacancies。

当我删除Company时,我想删除相对于它的Vacancies。

这是我的 Controller

  public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Company companies = db.Companies.Find(id);
if (companies == null)
{
return HttpNotFound();
}
return View(companies);
}

// POST: Companies/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
Company companies = db.Companies.Find(id);
db.Companies.Remove(companies);
db.SaveChanges();
return RedirectToAction("Index");
}

这是公司表

CREATE TABLE [dbo].[Companies] (
[CompanyID] INT IDENTITY (1, 1) NOT NULL,
[CompanyName] NVARCHAR (MAX) NULL,
PRIMARY KEY CLUSTERED ([CompanyID] ASC)

);

职位空缺

CREATE TABLE [dbo].[Vacancies] (
[VacancyId] INT IDENTITY (1, 1) NOT NULL,
[VacancyName] NCHAR (10) NULL,
[CompanyID] INT NULL,
PRIMARY KEY CLUSTERED ([VacancyId] ASC),
CONSTRAINT [FK_Vacancies_ToTable] FOREIGN KEY ([CompanyID]) REFERENCES [dbo].[Companies] ([CompanyID])

);

我需要如何修改语法才能轻松删除公司?

最佳答案

修改你的依赖添加ON DELETE CASCADE

CREATE TABLE [dbo].[Vacancies] (
[VacancyId] INT IDENTITY (1, 1) NOT NULL,
[VacancyName] NCHAR (10) NULL,
[CompanyID] INT NULL,
PRIMARY KEY CLUSTERED ([VacancyId] ASC),
CONSTRAINT [FK_Vacancies_ToTable]
FOREIGN KEY ([CompanyID])
REFERENCES [dbo].[Companies] ([CompanyID])
ON DELETE CASCADE);

这将允许在您删除公司时删除您的引用资料。或者,您可以将每个实体标记为已从 C# 中删除,这将为您提供更多控制并避免意外删除

关于c# - DELETE 语句冲突(ASP.NET MVC),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42843761/

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