0

I am trying to create a model to represent missions in a game. When a mission is completed, another mission is played depending on which team won the mission. For example Mission1, if TeamA wins then you play Mission2, if TeamB wins then you play Mission3.

For each mission I want two self-referencing columns, TeamAWinMission and TeamBWinMission, which hold the foreign key to another mission.

The migrations only seem to recognise a single self-reference in the model.

This will create a column for TeamAWinMission:

public class Mission
{
    public int Id { get; set; }

    public string Name { get; set; }

    public Mission TeamAWinMission{ get; set; }
}

This will only create a column for TeamBWinMission:

public class Mission
{
    public int Id { get; set; }

    public string Name { get; set; }

    public Mission TeamAWinMission{ get; set; }

    public Mission TeamBWinMission{ get; set; }
}

How can I make the migration generate columns/foreign keys for both of these?

Edit: Was able to resolve this with InverseProperty from https://stackoverflow.com/a/46832490/11575271

boxedi
  • 23
  • 2
  • 3
  • https://stackoverflow.com/questions/32628958/multiple-self-referencing-relationships-in-entity-framework – Robin Webb Jul 18 '19 at 11:46
  • I tried that but I receive 'Unable to determine the relationship represented by navigation property 'Mission.TeamAWinMission' of type 'Mission'' which I assume is something different between EF6 and EF Core 2? – boxedi Jul 18 '19 at 17:41

1 Answers1

1

It seems that there is one-to-one self-reference relationship in Mission model , you could try to define the [ForeignKey]in your model like below :

public class Mission
{
    public int Id { get; set; }

    public string Name { get; set; }
    [ForeignKey("TeamAWinMission")]
    public int? TeamAWinMissionId { get; set; }
    public Mission TeamAWinMission { get; set; }

    [ForeignKey("TeamBWinMission")]
    public int? TeamBWinMissionId { get; set; }

    public Mission TeamBWinMission { get; set; }
}

Then use Include attribute to load related data in the controller :

public IActionResult Mission()
{
      var result = _context.Missions
                           .Include(m => m.TeamAWinMission)
                           .Include(m => m.TeamBWinMission)
                           .ToList();
      return View(result);
}

Reference : https://learn.microsoft.com/en-us/ef/core/querying/related-data

Xueli Chen
  • 11,987
  • 3
  • 25
  • 36