I'm having problems with having two foreign key references to the same table. The foreign key id fields are populated but the navigation fields and lists (the Team fields) are not - they are both null.
My classes are:
public class Team
{
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Fixture> HomeFixtures { get; set; }
public virtual ICollection<Fixture> AwayFixtures { get; set; }
}
public class Fixture
{
public int Id { get; set; }
public int HomeTeamId { get; set; }
public int AwayTeamId { get; set; }
public Team HomeTeam { get; set; }
public Team AwayTeam { get; set; }
}
and my dbContext
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public DbSet<Team> Teams { get; set; }
public DbSet<Fixture> Fixtures { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Fixture>()
.HasOne(f => f.HomeTeam)
.WithMany(t => t.HomeFixtures)
.HasForeignKey(t => t.HomeTeamId)
.OnDelete(Microsoft.EntityFrameworkCore.Metadata.DeleteBehavior.Restrict);
modelBuilder.Entity<Fixture>()
.HasOne(f => f.AwayTeam)
.WithMany(t => t.AwayFixtures)
.HasForeignKey(t => t.AwayTeamId)
.OnDelete(Microsoft.EntityFrameworkCore.Metadata.DeleteBehavior.Restrict);
}
}
I have tried adding [ForeignKey()]
attributes to the HomeTeam and AwayTeam properties but it has no effect.
I have also tried changing the OnModelCreating method to work the other way, i.e.
modelBuilder.Entity<Team>()
.HasMany(t => t.HomeFixtures)
.WithOne(f => f.HomeTeam)
.HasForeignKey(f => f.HomeTeamId)
.OnDelete(Microsoft.EntityFrameworkCore.Metadata.DeleteBehavior.Restrict);
and the same for away fixtures but this produces identical behaviour.
It doesn't seem to matter how I query but the simplest case is
Fixture fixture = await _context.Fixtures.SingleOrDefaultAsync(f => f.Id == id);
The returned fixture object contains team Ids that are valid and in the database but the Team objects are still not populated.
Has anyone any idea what I'm doing wrong? This is a brand new project and a brand new database so there's no legacy code interfering. I'm using Visual Studio 2017rc with Entity Framework Core.