RationalGeek
RationalGeek

Reputation: 9609

EF Code First - linking entity to same dependent entity - delete cascade error

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?

Upvotes: 0

Views: 215

Answers (1)

Ben Tidman
Ben Tidman

Reputation: 2139

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

Upvotes: 1

Related Questions