开发者

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 pro开发者_如何学运维perty 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 =)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜