简体   繁体   English

EF核心一对多关系列表返回null

[英]EF Core One-to-Many relationship list returns null

I'm trying to learn how to properly utilize DbContext in EF Core. 我正在尝试学习如何在EF Core中正确使用DbContext。 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 而我的DbContext类包含

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. 我遇到的问题是,无论我做什么,Team.Mileages返回null且从不填充。
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: 如果我将List设置为不映射,请注入DbContext并尝试从上下文运行任何内容,它会引发以下错误:

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. 我正在使用MySQL,如果有任何区别。

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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM