简体   繁体   中英

How to make two foreign keys from a primary key of a table in Entity Framework Code First

My Scenario is, I have two tables called Person and RelationshipMappings. In Person table, PersonId is the primary key. In RelationshipMappings table, there are two integers LeftPersonId and RightPersonId. Both of these Ids should be ForeignKeys of PersonId.

I have created two Person Properties in the Relationship model called LeftPerson and RightPerson and then Created the table relationship like below.

 entityBuilder
           .HasOne(r => r.LeftPerson)
           .WithMany(r => r.RelationshipMappings)
           .HasForeignKey(r => r.LeftPersonId)
           .HasConstraintName("FK_RelationshipMapping_LeftPerson");


        entityBuilder
           .HasOne(r => r.RightPerson)
           .WithMany(r => r.RelationshipMappings)
           .HasForeignKey(r => r.RightPersonId)
           .HasConstraintName("FK_RelationshipMapping_RightPerson");

Should I have two collections in Person Model (LeftPerson and RightPerson)? Because Right now I have only one collection in the PersonModel.

  public ICollection<RelationshipMapping> RelationshipMappings { get; set; }

Also I have the relationship mentioned in the PersonModel also.

      entityBuilder
            .HasMany(e => e.RelationshipMappings)
            .WithOne(e => e.LeftPerson);

        entityBuilder
            .HasMany(e => e.RelationshipMappings)
            .WithOne(e => e.RightPerson);

Its not working for some reason. It fails to create the table and everything after that. I can't see the exception. I'm trying to find it out.

Could someone help me with this?

Okay, I found the solution. I had to add Delete Behavior in to the Foreign Keys.

           entityBuilder
           .HasOne(r => r.LeftPerson)
           .WithMany(r => r.LeftRelationshipMappings)
           .HasForeignKey(r => r.LeftPersonId)
           .HasConstraintName("FK_RelationshipMapping_LeftPerson")
           .OnDelete(DeleteBehavior.Restrict);


        entityBuilder
           .HasOne(r => r.RightPerson)
           .WithMany(r => r.RightRelationshipMappings)
           .HasForeignKey(r => r.RightPersonId)
           .HasConstraintName("FK_RelationshipMapping_RightPerson")
           .OnDelete(DeleteBehavior.Restrict);

Now everything works as expected. I had to have two collections though. It will not work with one collection. It will give below error.

Cannot create a relationship between 'Person.RelationshipMappings' and 'RelationshipMapping.RightPerson', because there already is a relationship between 'Person.RelationshipMappings' and 'RelationshipMapping.LeftPerson'. Navigation properties can only participate in a single relationship.

Thank you for the comments.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM