ASP.NET MVC 4 Multiple Foreign Keys Referencing Si

2019-05-16 15:54发布

问题:

I am trying to develop an ASP.NET MVC 4 application where players can be rated according to their Offence, Defence and Assist skills. Offence, Defence and Assist are foreign keys on Player table referencing the same lookup table - Rating.

I have the following parent entity:

public class Rating
{
    public int Id { get; set; }

    public string Name { get; set; }

    public virtual ICollection<Player> Players { get; set; }
}

And child entity:

public class Player
{
    public int Id { get; set; }

    public string Name { get; set; }

    public int OffenceRatingId { get; set; }
    [ForeignKey("OffenceRatingId")]
    public virtual Rating OffenceRating { get; set; }

    public int DefenceRatingId { get; set; }
    [ForeignKey("DefenceRatingId")]
    public virtual Rating DefenceRating { get; set; }

    public int AssistRatingId { get; set; }
    [ForeignKey("AssistRatingId")]
    public virtual Rating AssistRating { get; set; }
}

Building and scaffolding went fine but when I run the app, I get the following error:

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

I am new to MVC and have no idea what I am missing here. Any help with this will be greatly appreciated. Thanks.

回答1:

By default, Entity Framework has a Cascade on Delete convention. When two entities have foreign keys to each other, it causes a circular reference and Cascade on Delete can't be applied to both entities.

The simplest solution is to remove the cascade on delete convention, and apply it on a case by case basis.