搜尋

首頁  >  問答  >  主體

刪除外鍵條目的步驟

我有兩個表 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 天前498

全部回覆(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
  • 取消回覆