I have three model classes:
- User.
- Entry.
- EntryLikes.
As follows:
public class User
{
[Required]
public int ID { get; set; }
[Required]
[DataType(DataType.Text)]
public string Name { get; set; }
}
public class Entry
{
[Required]
public int ID { get; set; }
public int UserID { get; set; }
[ForeignKey("UserID")]
public virtual User User { get; set; }
}
public class EntryLike
{
[Required]
public int ID { get; set; }
[Required]
public int UserID { get; set; }
[ForeignKey("UserID")]
public virtual User User { get; set; }
[Required]
public int EntityID { get; set; }
[ForeignKey("EntityID")]
public virtual Entry Entry { get; set; }
}
Upon execution I got following exception:
Introducing FOREIGN KEY constraint
‘FK_dbo.EntryLikes_dbo.Entries_EntityID’ on table ‘EntryLikes’ may
cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or
ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints. Could
not create constraint. See previous errors.
Why do you have a foreign key relationship with User from EntryLike and from Entry? Given that you have a relationship between Entry and User on the Entry class, you don’t need one on the EntryLike class as it can be inferred due to the relationship between EntryLike and Entry. Also, should the foreign key id property on EntryLike be called EntryID rather than EntityID?
EDIT: It’s because you have multiple cascade paths to your User – one is Entry > User and the other is EntryLike > Entry > User. You will need to switch cascade delete off to stop this error from occurring. The links I put in the comment should get you on the right track.