简体   繁体   中英

Entity Framework - Introducing foreign key constraint may cause cycles

I'm developing an ASP.NET Core (2.0) Web App and I have the following two classes:

1.The team class

public class Team
{
    public int Id { get; set; }
    [Required]
    public string Name { get; set; }
    public string ImageUrl { get; set; }
}

2.And the Match class

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; }
}

When I try to update the database, I'm receive the following error:

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.

Turning one of the both foreign keys to optional is not an option. I saw multiples threads but they are, mostly, deprecated (ie they use DbModelBuilder or HasRequired).

How can I resolve this? Thank you!

I believe you still do it with a model builder as described here like this...

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; }
}

Restrict will do nothing which will result in an exception should you try and delete a Team referenced by one or more matches. Other alternatives are described here...

https://docs.microsoft.com/en-us/ef/core/saving/cascade-delete

I think that you should use fluent style to work with OnDelete . May be will help: https://www.learnentityframeworkcore.com/configuration/fluent-api/ondelete-method

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM