实体框架4.1:代码优先 - 外键限制错误

时间:2013-05-08 20:25:24

标签: entity-framework ef-code-first poco

我有一个基类,让我调用,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 inhertis来自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并在每个类Entity_B和Entity_C中添加'ID'属性时:

场景#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?

非常感谢!

0 个答案:

没有答案