Search code examples
c#.net-coreef-code-firstentity-framework-migrationsef-core-3.0

How to create a model with self reference in Entity Framework Code-First?


I'm using Entity Framework Core 3.1 and trying to handle simple scenario: In sport league there a many games, but I want to handle postponed games. This is my model:

public class Game
{
    public int GameId { get; set; }
    public DateTime StartTime { get; set; }
    public int HomeTeamId { get; set; }
    public int AwayTeamId { get; set; }
    public int? PostponedGameId { get; set; } // Original game that didn't happened and was postponed to 'this' game. 

    public Team HomeTeam { get; set; }
    public Team AwayTeam { get; set; }
    public Game PostponedGame { get; set; }
}

Obviously for most games PostponedGameId will be null.

How can I create a fluent API that will generate nullable FK (PostponedGameId)?

EDIT:

This is what I have so far:

        modelBuilder.Entity<Game>()
            .HasOne<Game>(g => g.PostponedGame)
            .WithOne()
            .OnDelete(DeleteBehavior.Cascade);

But I don't know how to I state that PostponedGameId is foreign key. I'm not even sure if this is correct, because I didn't run it without specifying foreign key.


Solution

  • So I would suggest something like the following:

    modelBuilder.Entity<Game>()
                .HasOne<Game>(g => g.PostponedGame)
                .WithOne()
                .HasForeignKey<Game>(g => g.PostponedGameId) // Defines the FK 
                .OnDelete(DeleteBehavior.Cascade)
                .IsRequired(false); // Tells ef-core that the FK is optional
    

    I am not able to verify the code at the moment, but it should work.