我正在开发一个ASP.NET Core(2.0)Web App,我有以下两个类:
1.团队班
public class Team
{
public int Id { get; set; }
[Required]
public string Name { get; set; }
public string ImageUrl { get; set; }
}
2.匹配课程
public class Match
{
public int Id { get; set; }
public DateTime Date { get; set; }
[Required]
public virtual Team Team1 { get; set; }
[Required]
public virtual Team Team2 { get; set; }
public int ScoreTeam1 { get; set; }
public int ScoreTeam2 { get; set; }
}
当我尝试更新数据库时,我收到以下错误:
Introducing FOREIGN KEY constraint 'FK_Matches_Teams_Team2Id' on table
'Matches' 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 or index. See previous errors.
将两个外键之一转为可选不是一个选项。 我看到了多个线程,但它们大部分被弃用(即它们使用DbModelBuilder或HasRequired)。
我该如何解决这个问题?谢谢!
答案 0 :(得分:2)
我相信您仍然可以使用像here这样描述的模型构建器...
public class MatchContext : DbContext
{
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder
.Entity<Match>()
.HasOne<Team>(e => e.Team1)
.WithMany(e => e.Matches)
.OnDelete(DeleteBehavior.Restrict);
}
}
public class Team
{
public int Id { get; set; }
[Required]
public string Name { get; set; }
public string ImageUrl { get; set; }
public ICollection<Match> Matches { get; set; }
}
public class Match
{
public int Id { get; set; }
public DateTime Date { get; set; }
[Required]
public virtual Team Team1 { get; set; }
[Required]
public virtual Team Team2 { get; set; }
public int ScoreTeam1 { get; set; }
public int ScoreTeam2 { get; set; }
}
如果您尝试删除由一个或多个匹配引用的Team,则Restrict将不执行任何会导致异常的操作。这里描述了其他替代方案......
https://docs.microsoft.com/en-us/ef/core/saving/cascade-delete
答案 1 :(得分:1)
我认为您应该使用流畅的风格来使用OnDelete
。可能会有所帮助:https://www.learnentityframeworkcore.com/configuration/fluent-api/ondelete-method