Home  >  Q&A  >  body text

Steps to remove a foreign key entry

I have two tables Employee and Address. Employee is my main table and Address is the child table related to Employee via the foreign key AddressId.

When I delete the Employee record, the record from Address is not deleted. How can I rewrite my code to do this?

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

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

This is my current code:

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粉845862826179 days ago359

reply all(1)I'll reply

  • P粉558478150

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

    You are looking for the ON DELETE CASCADE function, which will indicate to MySQL that a record should be deleted when its "parent" record (in another table) is deleted.

    Things like this:

    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
    );

    reply
    0
  • Cancelreply