Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enable cascading deletes in EF Code First without exposing foreign key

When performing a delete of a one-many relationship without exposing the foreign key, EF deletes the parent record and tries to null the foreign key on the child records. This of course causes an error because the foreign key is not nullable. Adding the foreign key to the child class overrides this behavior, but I'd rather not expose it.

For example given the following two classes, I'd prefer not to have JobId as a property of the Project class.

public class Job : ModelBase
{
    [Required]
    [StringLength(100)]
    public string Company { get; set; }

    [Required]
    [StringLength(100)]
    public string JobTitle { get; set; }

    public ICollection<Project> Projects { get; set; }
}

public class Project : ModelBase
{
    [Required]
    [StringLength(100)]
    public string Name { get; set; }

    [Required]
    public string Summary { get; set; }

    public int JobId { get; set; }
}

Is there a way to enable cascading deletes in EF Code First without exposing the foreign key on the many side of the relationship?

like image 415
Craig M Avatar asked Mar 20 '11 05:03

Craig M


People also ask

How do I enable cascade delete in Entity Framework?

Cascade delete automatically deletes dependent records or sets null to ForeignKey columns when the parent record is deleted in the database. Cascade delete is enabled by default in Entity Framework for all types of relationships such as one-to-one, one-to-many and many-to-many.

How does foreign key on delete cascade work?

A foreign key with cascade delete means that if a record in the parent table is deleted, then the corresponding records in the child table will automatically be deleted. This is called a cascade delete in SQLite. A foreign key with a cascade delete can only be defined in a CREATE TABLE statement.

Is Cascade delete default?

A cascade-delete bypasses security and sharing settings, which means users can delete records when the target lookup record is deleted even if they don't have access to the records. To prevent records from being accidentally deleted, cascade-delete is disabled by default.


1 Answers

Yup! Remove JobId and add the following:

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Job>().HasMany(j => j.Projects).WithRequired();
    }

In the database, this will add a cascading delete in the PK/FK relationship.

(I'm assuming that your ModelBase has an integer Id =)

like image 75
anon Avatar answered Oct 20 '22 12:10

anon