EF Code First allows cascading deletes without exposing foreign keys.

cascading-deletes code-first entity-framework one-to-many

Question

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?

1
14
3/20/2011 5:13:25 AM

Accepted Answer

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

14
3/20/2011 6:04:18 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow