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