EF核心一对多关系列表返回null [英] EF Core One-to-Many relationship list returns null

查看:220
本文介绍了EF核心一对多关系列表返回null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试学习如何在EF Core中正确利用DbContext。
我有一个团队课程:

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; }
}

和里程舱:

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; }
}

我的DbContext类包含

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

我遇到的问题是,无论我做什么, Team.Mileages返回null,并且从不填充。

如果将列表设置为不被映射,则注入DbContext并尝试从上下文中运行任何内容,它会引发以下错误:

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

我想念的明显的东西?我正在使用MySQL,如果有任何不同的话。

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

这篇关于EF核心一对多关系列表返回null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆