【问题标题】:How to delete on cascade EF core如何在级联 EF 核心上删除
【发布时间】:2020-10-04 15:53:36
【问题描述】:

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

我的模型

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;
}

【问题讨论】:

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


【解决方案1】:

您正在那里删除一对多关系的多方面。一切都按预期进行。

尝试删除Company

【讨论】:

  • 嗯,是的,你是对的。当我删除一家公司时,它正在工作。我怎样才能确保当我删除一个帖子时,其他帖子也被删除了?我是否总是需要删除多对一关系而不是一对多关系?
  • 您为什么要这样做?想象一下有人删除了一个帖子。您最终会删除与该帖子相关联的公司的所有内容。这就是你想要的吗?
  • 哦,哈哈,没关系。有点困惑。感谢您的澄清
猜你喜欢
  • 2021-08-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多