我正在尝试学习如何在EF Core中正确利用DbContext。 我有一个团队班:
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类包含
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并尝试从上下文中运行任何内容,它将引发以下错误:
在此之前,第二个操作在此上下文上开始 完成
我缺少一些明显的东西吗?我正在使用MySQL,如果有任何区别。
答案 0 :(得分:0)
默认情况下,实体框架使用惰性加载,您可以设置为渴望加载并始终加载引用,也可以在数据库请求中请求收集。 示例:
_dbcontext.Team.Include(team => team.Mileages).ToList();