1
votes

Using: VS 2013, Entity Framework Code First, ASP.NET Web Project MVC

I have 2 models, in one need 2 FK for the same table:

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; }
}

After enable-migration and Add-Migration Test, when I run Update-Database, I get this message:

Introducing FOREIGN KEY constraint 'FK_dbo.B_dbo.A_Id2' on table 'B' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.

1
I think, attributes are redundant, cuz EF treats Id1 and Id2 props as a keys for appropriate entities.Eugene P.

1 Answers

1
votes

use this code

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)
                    ;       
    }

alse you could use inverseProperty attribute.