I don't understand why the following code throws the following error:
System.Data.SqlClient.SqlException: „Introducing FOREIGN KEY constraint 'FK_dbo.CategoryUserRoles_dbo.AspNetUsers_GivenByUserId' on table 'CategoryUserRoles' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.
The InverseProperty
tag should fix this, but for some reason in this case it doesn't. Perhaps it's because it's used in the ApplicationUser
which inherits from IdentityUser
?
If I comment out the GivenByUser
section, then everything works fine.
Here's the code:
public class ApplicationUser : IdentityUser
{
//Relationships
[InverseProperty("User")]
public ICollection<CategoryUserRole> CategoryUserRoles { get; set; }
[InverseProperty("GivenByUser")]
public ICollection<CategoryUserRole> CategoryUserRolesIGave { get; set; }
}
public class Category
{
[Key]
[Required]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[Required]
[MaxLength(256)]
[Index(IsUnique = true)]
public string Name { get; set; }
[Required]
[MaxLength(1024)]
public string Description { get; set; }
[Required]
public DateTime DateAdded { get; set; }
//Relationships
[InverseProperty("Category")]
public ICollection<CategoryUserRole> CategoryUserRoles { get; set; }
}
public class CategoryUserRole
{
[Key]
[Required]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[Required]
public string Role { get; set; }
[Required]
public DateTime DateGiven { get; set; }
//Relationships
[Required]
public string UserId { get; set; }
[ForeignKey("UserId")]
public ApplicationUser User { get; set; }
[Required]
public int CategoryId { get; set; }
[ForeignKey("CategoryId")]
public Category Category { get; set; }
// ---- everything works fine after commenting out this section -----
[Required]
public string GivenByUserId { get; set; }
[ForeignKey("GivenByUserId")]
public ApplicationUser GivenByUser { get; set; }
}
// EDIT: This question has been marked as a duplicate of a 4-years-old question Introducing FOREIGN KEY constraint may cause cycles or multiple cascade paths - why? But back then the InverseProperty was not present. According to the InverseProperty section on this website https://learn.microsoft.com/en-us/ef/core/modeling/relationships it should be possible to define such relation without having to use Fluent. So my question remains unanswered.