如何在级联EF核心上删除

时间:2020-10-04 15:53:36

标签: c# .net entity-framework-core webapi

删除行时,我试图删除彼此相关的实体,但是并没有删除相关的实体。它只是删除一个实体,而不删除其他实体。

我的模特

public class Company
{
    public int CompanyId { get; set;}
    public string CompanyName { get; set; }
    public int CompanySize { get; set; }
    public string Branche { get; set;}
    public string Description {get; set;}
    public Recruiter Recruiter { get; set; }
    public ICollection<Post> Posts { get; set; }

}

public class Recruiter
{
    public int RecruiterId { get; set; }
    public string Name { get; set; }
    public string Email { get; set; }
    public string PhoneNumber { get; set; }
    public int CompanyId { get; set; }
    public Company Company { get; set; }
}

public class Post
{
    public int PostId { get; set; }
    public string Title { get; set; }
    public string Location { get; set; }
    public int Compensation { get; set; }
    public string Education { get; set; }
    public string StartDate { get; set; }
    public string Type { get; set; }
    public string Profession { get; set; }
    public string Language { get; set; }
    public string Description { get; set; }
    public string Hours { get; set; }
    public bool Checked { get; set; }
    public int CompanyId { get; set; }
    public Company Company { get; set; }
}

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Post>()
        .HasOne(post => post.Company)
        .WithMany(company => company.Posts)
        .IsRequired()
        .OnDelete(DeleteBehavior.Cascade);
    
    modelBuilder.SeedDatabase();
}

我打的电话。因此,当我删除帖子时,我希望所有相关实体都被删除。


public Post DeclinePostRequest(int postId)
{
    var request = _dbContext.Posts.Where(post => post.PostId == postId).Include(post => post.Company).ThenInclude(company => company.Recruiter).FirstOrDefault();
    if(!request.Checked)
    {
        _dbContext.Posts.Remove(request);
        _dbContext.SaveChanges();
        return request;
    }
    return null;
}

1 个答案:

答案 0 :(得分:1)

您要删除一对多关系的许多方面。一切都按预期进行。

尝试删除Company