该数据模型符合我的要求吗?

时间:2018-10-23 22:05:22

标签: c# entity-framework-core

我正在创建一个类似于“曲棍球联盟”的Razor Pages应用程序。由于我仍在掌握外键/主键的概念,因此不确定是否正确设置了数据模型。迁移后尝试更新数据库后,出现以下错误,使我相信我没有正确设置它们:

  

在表'Team'上引入FOREIGN KEY约束'FK_Team_Division_DivisionID'可能会导致循环或多个级联路径。指定ON DELETE NO ACTION或ON UPDATE NO ACTION,或修改其他FOREIGN KEY约束。

基于这三个实体,我显然做错了吗?

public class Team
{
    public int ID { get; set; }
    public int? CoachID { get; set; }
    public int? DivisionID { get; set; }
    public int? ConferenceID { get; set; }

    [Display(Name = "Team")]
    public string TeamName { get; set; }

    [Display(Name = "Location")]
    public string TeamLocation { get; set; }

    public Coach Coach { get; set; }
    public Division Division { get; set; }
    public Conference Conference { get; set; }

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

public class Conference
{
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int ID { get; set; }

    [Display(Name = "Conference")]
    public string ConferenceName { get; set; }

    public ICollection<Division> Divisions { get; set; }
    public ICollection<Team> Teams { get; set; }        
}

public class Division
{
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int ID { get; set; }
    public int ConferenceID { get; set; }

    [Display(Name = "Division")]
    public string DivisionName { get; set; }

    public Conference Conference { get; set; }

    public ICollection<Team> Teams { get; set; }

}

我的想法是,每个Team将分别属于ConferenceDivisionTeams中可以有许多Division,而Divisions中可以有许多Conference

1 个答案:

答案 0 :(得分:4)

您遇到的问题是SQL Server不知道如何处理具有多个父项的项的Delete。您需要一点帮助。选择您要删除Team的路由,例如:

Conference --> Division --> Team

然后,您必须确定要删除的路由,例如:

Conference --> Team

一旦您决定不使用哪些路由 ,您可以根据自己的情况在OnModelCreating(DbModelBuilder modelBuilder)方法中指定它

modelBuilder.Entity<Conference>() 
    .HasRequired(x => x.Team)     
    .WithMany()
    .WillCascadeOnDelete(false);

编辑

很确定我在上面已经倒退了,试试这个:

modelBuilder.Entity<Team>() 
    .HasRequired(x => x.Conference)     
    .WithMany()
    .WillCascadeOnDelete(false);