搜索

首页  >  问答  >  正文

删除外键条目的步骤

我有两个表 EmployeeAddressEmployee 是我的主表,Address 是通过外键 AddressIdEmployee 关联的子表。

当我删除 Employee 记录时,来自 Address 的记录不会被删除。我如何重写我的代码来做到这一点?

Employee:
  [Id](Primary Key)
  [FirstName] 
  [LastName]
  [Email]
  [AddressId] (Foreign Key -> Address.Id)
  [Code]

Address:
  [Id] (Primary Key)
  [Details]
  [State]
  [Country]

这是我当前的代码:

public bool DeleteEmployee(int id)
{
            using (var context=new EmployeeDBEntities())
            {
                var employee = context.Employee.FirstOrDefault(x => x.Id == id);
               
                if (employee != null)
                {
                    context.Employee.Remove(employee);
                    context.SaveChanges();
                    return true;
                }
                return false;
            }
        }

P粉845862826P粉845862826259 天前499

全部回复(1)我来回复

  • P粉558478150

    P粉5584781502024-04-05 10:33:38

    您正在寻找 ON DELETE CASCADE 功能,该功能将向 MySQL 指示当删除其“父”记录(在另一个表中)时应删除该记录。

    类似这样的事情:

    CREATE TABLE address (
        Id INT PRIMARY KEY AUTO_INCREMENT,
        Details VARCHAR(255) NOT NULL,
        State VARCHAR(255) NOT NULL,
        Country VARCHAR(255) NOT NULL
    );
    
    CREATE TABLE employee (
        Id INT PRIMARY KEY AUTO_INCREMENT,
        FirstName VARCHAR(255) NOT NULL,
        LastName VARCHAR(255) NOT NULL,
        Email VARCHAR(255) NOT NULL,
        AddressId INT NOT NULL,
        Code VARCHAR(255) NOT NULL,
        FOREIGN KEY (AddressId)
            REFERENCES address (Id)
            ON DELETE CASCADE
    );

    回复
    0
  • 取消回复