1

I'm trying to create an API to manage soccer matches. I'm using Entity Framework Core with code-first approach and Domain Driven Design (DDD). I'm stuck with the relationship between Player and Match.

Basically, every match has 2 players (Host and Guest), so I've tried to point 2 FKs (HomePlayerId, GuestPlayerId) to the same table, but I get an exception:

Unable to determine the relationship represented by navigation 'Match.HomePlayer' of type 'Player'. Either manually configure the relationship, or ignore this property using the '[NotMapped]' attribute or by using 'EntityTypeBuilder.Ignore' in 'OnModelCreating'.

Player class:

public class Player : Entity
{
        private  List<Match> _matches;

        public string Name { get; private set; }
        public Team Team { get; private set; }

        public Group Group { get; private set; }

        public IReadOnlyCollection<Match> Matches { get => _matches.ToArray(); }

        public Player(string name, Team team)
        {
            Name = name;
            Team = team;
            _matches = new List<Match>();
        }

        protected Player() { }
}

Match class:

public class Match : Entity
{
        public Guid HomePlayerId { get; private set; }
        public Player HomePlayer { get; private set; }
        public Guid GuestPlayerId { get; private set; }
        public Player GuestPlayer { get; private set; }
        public int GoalsHomeTeam { get; private set; }
        public int GoalsGuestTeam { get; private set; }
        public DateTime MatchDate { get; private set; }

        public Match(Player homePlayer, Player guestPlayer, int goalsHomeTeam, int goalsGuestTeam)
        {
            HomePlayer = homePlayer;
            GuestPlayer = guestPlayer;
            GoalsHomeTeam = goalsHomeTeam;
            GoalsGuestTeam = goalsGuestTeam;
            MatchDate = DateTime.Now;
        }

        protected Match() { }
}

Base entity:

public abstract class Entity : IEntity
{
    protected Entity()
    {
        Id = Guid.NewGuid();
    }

    public Guid Id { get; set; }
}

DbContext:

public class ApplicationDbContext : DbContext
{
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> opt) : base(opt)
    {
    }

    public DbSet<Group> Groups { get; set; }
    public DbSet<Player> Players{ get; set; }
    public DbSet<Match> Matches{ get; set; }
    public DbSet<Team> Teams{ get; set; }

    protected override void OnModelCreating(ModelBuilder builder)
    {
    }
}

How can I build my models in order to create that relationship?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459

0 Answers0