2

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

计算机实体:

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

2 回答 2

2

您需要使用 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 配置关系

于 2013-02-10T05:30:25.230 回答
0

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

于 2013-02-08T14:20:11.677 回答