0

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.

Vy Do
  • 46,709
  • 59
  • 215
  • 313
Ish Thomas
  • 2,270
  • 2
  • 27
  • 57
  • Does [this](https://learn.microsoft.com/en-us/ef/core/modeling/relationships?tabs=fluent-api%2Cfluent-api-simple-key%2Csimple-key#required-and-optional-relationships) help you? – Twenty Feb 02 '20 at 01:22
  • @Twenty not exactly. In this post there is self reference, but "one to many". I need "one to one" self reference. – Ish Thomas Feb 02 '20 at 01:26
  • I am talking about the `.IsRequired()` method. – Twenty Feb 02 '20 at 01:33
  • @Twenty I don't get it. It's not required. Most games are not postponed – Ish Thomas Feb 02 '20 at 01:34
  • The `IsRequired` method takes a boolean parameter which defines if the FK is required or not. – Twenty Feb 02 '20 at 01:35
  • @Twenty I didn't even specify the FK. Look at my edit – Ish Thomas Feb 02 '20 at 01:36
  • Does this answer your question? [What is the syntax for self referencing foreign keys in EF Code First?](https://stackoverflow.com/questions/4811194/what-is-the-syntax-for-self-referencing-foreign-keys-in-ef-code-first) – devNull Feb 02 '20 at 01:39
  • @devNull There is `modelBuilder.Entity().HasOptional(c => c.Spouse).WithMany().HasForeignKey(c => c.SpouseId);` why `WithMany`? I don't get it, because it's one-to-one – Ish Thomas Feb 02 '20 at 01:43

1 Answers1

2

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.

Twenty
  • 5,234
  • 4
  • 32
  • 67