关于删除的EF5 Code First Cascade

当我删除计算机时,有没有办法在删除时获得级联? 基本上当我删除一台计算机时,我希望它删除实例及其所有引用,除了环境和产品。

计算机实体:

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(); Environments = new HashSet(); } [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 TestResults { get; set; } public virtual ICollection Environments { get; set; } } 

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

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

在MSDN上很好地记录了这一点: 使用Fluent API配置关系

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