0

我有一个基类,让我调用Entity_A,它只有一个属性“ID”,它是主键。

public abstract class Entity_A
{
   [Key(), Required]
   [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
   public Guid ID { get; set; }
}

然后我有另外两个类,Entity_B 和 Entity_C。

Entity_B 和 Entity_C 从 Entity_A 继承:

场景#1:

[Table("Entity_B")]
public class Entity_B : Entity_A
{
    [Required]
    public virtual string propertyB1 { get; set; }

    // Below foreign key
    [Required]
    [ForeignKey("propertyB2")]
    public virtual Guid propertyB2Id { get; set; }
    public virtual Entity_C propertyB2 { get; set; }
}

[Table("Entity_C")]
public class Entity_C : Entity_A
{
    [Required]
    public virtual string propertyC1 { get; set; }

    [Required]
    public virtual string propertyC2 { get; set; }
}

它工作正常,它创建了表格。我的问题是当我删除 Entity_A 并将“ID”属性放在每个类 Entity_B 和 Entity_C 中时:

场景#2:

[Table("Entity_B")]
public class Entity_B
{
    [Key(), Required]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public Guid ID { get; set; }

    [Required]
    public virtual string propertyB1 { get; set; }

    // Below foreign key
    [Required]
    [ForeignKey("propertyB2")]
    public virtual Guid propertyB2Id { get; set; }
    public virtual Entity_C propertyB2 { get; set; }
}

[Table("Entity_C")]
public class Entity_C
{
    [Key(), Required]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public Guid ID { get; set; }

    [Required]
    public virtual string propertyC1 { get; set; }

    [Required]
    public virtual string propertyC2 { get; set; }
}

当我执行时,会引发异常:

Introducing FOREIGN KEY constraint 'Entity_B_propertyB2' on table 'Entity_B' may
cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO 
ACTION, or modify other FOREIGN KEY constraints. Could not create constraint. See 
previous errors.

我通过覆盖 OnModelCreating 方法来解决它:

// TURN OFF ON DELETE CASCADE GLOBALY BY REMOVING THE CONVENTION 
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
     modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();  
}

我的问题是:

1) 为什么实体框架的行为不同于场景#1(它工作的地方)和场景#2(它不工作的地方)?

2) 如果我不关闭删除级联约定,为什么在场景 #2 中不起作用?如果我关闭它,这是一个好习惯吗?我想知道它是坏的还是好的。另外,有没有办法让它工作而不需要覆盖 OnModelCreating?

非常感谢!

4

0 回答 0