删除时EF5代码第一级联

本文关键字:级联 代码 EF5 删除 | 更新日期: 2023-09-27 17:58:16

当我删除计算机时,有什么方法可以实现级联删除吗?基本上,当我删除一台计算机时,我希望它删除该实例及其除环境和产品之外的所有引用。

计算机实体:

public class Computer
{
    [Key]
    public int Id { get; set; }
    public string IpAddress { get; set; }
    public string Name { get; set; }
    public string UserFriendlyName { get; set; }
    public string Description { get; set; }
}

实例实体:

    public class Instance
{
    public Instance()
    {
        TestResults = new HashSet<TestResult>();
        Environments = new HashSet<Environment>();
    }
    [Key]
    public int Id { get; set; }
    public string Name { get; set; }
    public string Version { get; set; }
    public string UserFriendlyName { get; set; }
    public virtual Product Product { get; set; }
    public virtual Profile LastKnownProfile { get; set; }
    public virtual Computer Computer { get; set; }
    public virtual ICollection<TestResult> TestResults { get; set; }
    public virtual ICollection<Environment> Environments { get; set; } 
}

删除时EF5代码第一级联

您需要使用Fluent API定义关系。使用类似的东西:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
  modelBuilder.Entity<Computer>()
                .HasRequired(x => x.Instance)
                .WithRequiredPrincipal(x => x.Computer)
                .WillCascadeOnDelete();
  modelBuilder.Entity<Instance>()
                .HasRequired(x => x.LastKnownProfile)
                .WithRequiredPrincipal(x => x.Instance)
                .WillCascadeOnDelete();
  modelBuilder.Entity<Instance>()
                .HasMany(x => x.TestResults)
                .WithOptional(x => x.Instance)
                .WillCascadeOnDelete();
}

这在MSDN上有很好的记录:使用Fluent API 配置关系

检查多对多关系。关闭状态的级联删除并手动删除相关记录。