C# EF5代码在删除时第一次级联

C# EF5代码在删除时第一次级联,c#,entity-framework,C#,Entity Framework,当我移除一台计算机时,有没有任何方法可以让删除发生级联?基本上,当我删除一台计算机时,我希望它删除实例及其所有引用(环境和产品除外) 计算机实体: public class Computer { [Key] public int Id { get; set; } public string IpAddress { get; set; } public string Name { get; set; } public string UserFriend

当我移除一台计算机时,有没有任何方法可以让删除发生级联?基本上,当我删除一台计算机时,我希望它删除实例及其所有引用(环境和产品除外)

计算机实体:

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; } 
}
公共类实例
{
公共实例()
{
TestResults=newhashset();
环境=新的HashSet();
}
[关键]
公共int Id{get;set;}
公共字符串名称{get;set;}
公共字符串版本{get;set;}
公共字符串UserFriendlyName{get;set;}
公共虚拟产品产品{get;set;}
公共虚拟配置文件LastKnown配置文件{get;set;}
公共虚拟计算机{get;set;}
公共虚拟ICollection测试结果{get;set;}
公共虚拟ICollection环境{get;set;}
}

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

您需要使用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();
}
模型创建时受保护的覆盖无效(DbModelBuilder modelBuilder)
{
modelBuilder.Entity()
.HasRequired(x=>x.Instance)
.WithRequiredPrincipal(x=>x.Computer)
.WillCascadeOnDelete();
modelBuilder.Entity()
.HasRequired(x=>x.LastKnown配置文件)
.WithRequiredPrincipal(x=>x.Instance)
.WillCascadeOnDelete();
modelBuilder.Entity()
.HasMany(x=>x.TestResults)
.WithOptional(x=>x.Instance)
.WillCascadeOnDelete();
}

这在MSDN上有很好的记录:

是的,它已关闭。但是,我更关心的是如何将其配置为在计算机被删除时删除实例。