I'm trying to learn how to properly utilize DbContext in EF Core. I have a Team class:
public class Team
{
public int ID { get; set; }
public string Name { get; set; }
public bool CanSelfManage { get; set; } = false;
public virtual List<Mileage> Mileages { get; set; }
public IdentityUser Member { get; set; }
public string State { get; set; }
public List<Horse> Horses { get; set; }
}
And a Mileage class:
public class Mileage
{
public int ID { get; set; }
public virtual Team Team { get; set; }
public virtual int TeamID { get; set; }
public DateTime Date { get; set; }
public LogType Type { get; set; }
public decimal Miles { get; set; }
public IdentityUser User { get; set; }
public List<Horse> Horses { get; set; }
}
And my DbContext class contains
public DbSet<Team> Teams { get; set; }
public DbSet<Mileage> Mileages { get; set; }
public DbSet<Horse> Horses { get; set; }
public DbSet<SecurityEntry> SecurityEntries { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Mileage>()
.HasOne(t => t.Team)
.WithMany(b => b.Mileages)
.HasForeignKey(t => t.TeamID)
.IsRequired();
modelBuilder.Entity<Horse>()
.HasOne(t => t.Team)
.WithMany(h => h.Horses);
modelBuilder.Entity<Horse>()
.HasMany(m => m.Mileages);
modelBuilder.Entity<Mileage>()
.HasMany(h => h.Horses);
}
The problem that I'm having is that, no matter what I do, Team.Mileages returns null and is never populated.
If I set the List to not be mapped, inject the DbContext and try to run anything off of the context, it throws the following error:
A second operation started on this context before a previous operation completed
Is there something glaring that I'm missing? I am using MySQL, if that makes any difference.
Entity framework by default uses Lazy loading, you either set to eager loading and load your references always or you ask for your collections on a database request. Example:
_dbcontext.Team.Include(team => team.Mileages).ToList();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With