【问题标题】:Entity Framework Many to Many Cascade Delete One Way实体框架多对多级联删除一种方式
【发布时间】:2016-02-22 16:58:07
【问题描述】:

我有 2 个实体:报告和文件请求。它们之间存在多对多的关系。

所以 Report.cs 有

 public virtual ICollection<FileRequest> FileRequests { get; set; }

而且 FileRequest.cs 有

 public ICollection<Report> Reports { get; set; }

Entity Framework 已生成连接表 (FileRequestReports),级联删除始终适用于连接表条目。 我想要发生的是删除文件请求会删除关联的报告,但删除报告不会删除关联的文件请求。应始终删除关联的连接表条目。

注意:ManyToManyCascadeDeleteConvention 已开启。

是否有相对简单的方法来处理 EF 和级联删除?

提前致谢。

【问题讨论】:

  • FileRequestReports中还有其他信息吗?通常自动生成的多对多表使用两个相关表的 Id 作为键。如果删除关系的一端,则设置为级联删除,因为外键约束会失败。为了完成这项工作,您需要创建自己的 FileRequestReport 实体,为其指定唯一键,使 ReportId 字段为必填字段,并使 FileRequestId 可为空。
  • 不,FileRequestReports 只包含两个外键

标签: c# entity-framework


【解决方案1】:

我相信实现这一点的唯一方法是创建一个类来表示多对多关系。像这样:

public class ReportFileRequest
{
    public int ReportId { get; set; }

    public int FileRequestId { get; set;}

    public virtual Report Report { get; set;}

    public virtual FileRequest FileRequest { get; set; }
}

你要更新Report:

public virtual ICollection<ReportFileRequest> ReportFileRequests { get; set; }

还有FileRequest:

public virtual ICollection<ReportFileRequest> ReportFileRequests { get; set; }

映射:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<ReportFileRequest>()
        .HasKey(i => new { i.ReportId, i.FileRequestId });

    model.Entity<ReportFileRequest>()
       .HasRequired(i => i.Report)
       .WithMany(i => i.ReportFileRequests)
       .WithForeignKey(i => i.ReportId)
       .WillCascadeOnDelete(true);

    model.Entity<ReportFileRequest>()
       .HasRequired(i => i.FileRequest)
       .WithMany(i => i.ReportFileRequests)
       .WithForeignKey(i => i.FileRequestId)
       .WillCascadeOnDelete(false);

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-10
    • 1970-01-01
    • 2021-12-10
    • 2014-12-20
    • 1970-01-01
    相关资源
    最近更新 更多