删除外键条目的步骤
P粉845862826
P粉845862826 2024-04-04 14:15:44
0
1
446

我有两个表 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粉845862826
P粉845862826

全部回复(1)
P粉558478150

您正在寻找 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
);
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板