EF Code First allows cascading deletes without exposing foreign keys.

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

Question

EF deletes the parent record and attempts to null the foreign key on the child records when deleting a one-many connection without revealing the foreign key. Since the foreign key cannot be nullified, this naturally results in an error. This behavior may be overridden by adding the foreign key to the child class, but I'd want to keep it hidden.

I would like not to have JobId as a property of the Project class, given the following two classes.

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 it possible to use EF Code First to allow cascade deletes without disclosing the foreign key on the other side of the relationship?

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

Accepted Answer

Yup! Replacing JobId with the following

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

This will add a cascading delete to the PK/FK relationship in the database.

(I'm assuming that the integer Id = in your ModelBase)

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