0
votes

I have these two entities:

public class Profile
{
    public int ProfileID { get; set; }

    public ICollection<Friend> Friends { get; set; }
}

public class Friend : BaseEntity
{
    public int FriendID { get; set; }

    public int ProfileID { get; set; }
    [ForeignKey("ProfileID")]
    public Profile Profile { get; set; }

    public int FriendProfileID { get; set; }
    [ForeignKey("FriendProfileID")]
    public Profile FriendProfile { get; set; }
}

I think it is clear what I'm looking to do. I want a Profile to be able to have a collection of Friends that reference other profiles. Without specifying anything in the OnModelCreating, I get the following error:

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

So that means I need to specify a WillCascadeOnDelete(false) using the fluent API in the OnModelCreating method on the context. However, I can't seem to figure out the right syntax using these relationships.

How do I resolve the cascade delete cycle and get entity framework to tolerate this relationship?

1
Are you trying to make Profile.Friends the other end of the navigation properties Friend.Profile and Friend.FriendProfile? Or is it just for one of them, or none of them?Ben Tidman
Trying to make it the other end of Friend.Profile.RationalGeek

1 Answers

1
votes

You are right that you need to add a fluent mapping to OnModelCreating(). Try something like this:

modelBuilder.Entity<Friend>()
                .HasOptional(x => x.FriendProfile )  //or HasRequired
                .WithMany()
                .WillCascadeOnDelete(false);