ASP.NET MVC 4 Multiple Foreign Keys Referencing Single Parent Entity

孤街浪徒 提交于 2019-12-07 11:58:44

问题


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.



来源:https://stackoverflow.com/questions/12926675/asp-net-mvc-4-multiple-foreign-keys-referencing-single-parent-entity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!