“引入FOREIGN KEY约束”

时间:2014-02-19 19:20:57

标签: entity-framework code-first

使用:VS 2013,实体框架代码优先,ASP.NET Web项目MVC

我有2个型号,同一个表需要2个FK:

public class A
{
    public int Id { get; set; }
    public string  Name { get; set; }
}
public class B
{
    public int Id { get; set; }

    public int Id1 { get; set; }

    [ForeignKey("Id1")]
    public virtual A A1 { get; set; }

    public int Id2 { get; set; }

    [ForeignKey("Id2")]
    public virtual A A2 { get; set; }
}

enable-migrationAdd-Migration Test之后,当我运行Update-Database时,我收到此消息:

  

在表'B'上引入FOREIGN KEY约束'FK_dbo.B_dbo.A_Id2'可能会导致循环或多个级联路径。指定ON DELETE NO ACTION或ON UPDATE NO ACTION,或修改其他FOREIGN KEY约束。

1 个答案:

答案 0 :(得分:0)

使用此代码

public class A
{
    public int Id { get; set; }
    public string  Name { get; set; }
}
public class B
{
    public int Id { get; set; }

    public int Id1 { get; set; }

    [ForeignKey("Id1")]
    public virtual A A1 { get; set; }

    public int Id2 { get; set; }

    [ForeignKey("Id2")]
    public virtual A A2 { get; set; }
}

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<B>()
                    .HasRequired(e => e.A1)
                    .WithMany()
                    .HasForeignKey(c => c.Id1)
                    .WillCascadeOnDelete(false)

                    .HasRequired(e => e.A2)
                    .WithMany()
                    .HasForeignKey(c => c.Id2)
                    .WillCascadeOnDelete(false)
                    ;       
    }

另外你可以使用inverseProperty属性。