我有ASP.NET MVC应用程序
我有两张相关的公司和职位空缺表。
当我删除公司时,我想删除相对于它的职位空缺。
这是我的控制器
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)
);
An•职位空缺
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])
);
我如何修改语法以轻松删除公司?
答案 0 :(得分:1)
修改您的从属项以添加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#中删除,这将为您提供更多控制并避免意外删除