gpt4 book ai didi

c# - EF Core 一对多关系列表返回 null

转载 作者:太空宇宙 更新时间:2023-11-03 12:05:36 25 4
gpt4 key购买 nike

我正在尝试学习如何在 EF Core 中正确使用 DbContext。我有一个团队类(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; }
}

还有一个 Mileage 类:

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 类包含

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 并且永远不会被填充。
如果我将 List 设置为不映射,注入(inject) DbContext 并尝试在上下文之外运行任何东西,它会抛出以下错误:

A second operation started on this context before a previous operation completed

我是否遗漏了什么明显的东西?我正在使用 MySQL,如果这有什么不同的话。

最佳答案

Entity Framework 默认使用延迟加载,您要么设置为预先加载并始终加载您的引用,要么在数据库请求时请求您的集合。示例:

_dbcontext.Team.Include(team => team.Mileages).ToList();

关于c# - EF Core 一对多关系列表返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55210832/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com