Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple Associations from one Object to two Objects of the same Entity Type

I am attempting to use code first and the fluent API to create an object that holds two different entities from the same table. In other words, a transfer object holds a reference to two different tank objects--one is the source and the other the destination.

However, when I use the following code I get an Exception stating that "The referential relationship will result in a cyclical reference that is not allowed."

modelBuilder.Entity<Transfer>()
            .HasRequired<Tank>(t => t.Source)
            .WithMany(t => t.OutboundTransfers);
modelBuilder.Entity<Transfer>()
            .HasRequired<Tank>(t => t.Destination)
            .WithMany(t => t.InboundTransfers);

My best guess is that it thinks I am pointing both keys to the same Tank? Any idea how I can accomplish this?

EDIT: Found the answer as adding .WillCascadeOnDelete(false) from Entity Framework Code First - two Foreign Keys from same table

like image 895
Matthew Avatar asked May 13 '11 01:05

Matthew


1 Answers

As you stated, you should be able to add .WillCascadeOnDelete(false) - https://stackoverflow.com/a/5559300/5416

modelBuilder.Entity<Transfer>()
        .HasRequired<Tank>(t => t.Source)
        .WithMany(t => t.OutboundTransfers)
        .WillCascadeOnDelete(false);
modelBuilder.Entity<Transfer>()
        .HasRequired<Tank>(t => t.Destination)
        .WithMany(t => t.InboundTransfers)
        .WillCascadeOnDelete(false);

I just added this answer so that it doesn't show on the unanswered list any more as unanswered with zero answers. Marked as community wiki :)

like image 182
2 revs Avatar answered Oct 21 '22 10:10

2 revs