实体框架 - 加载不启动

时间:2016-12-03 20:05:43

标签: c# asp.net-mvc entity-framework

我正在制作梦幻足球游戏,我正在使用Entity Framework来映射我的数据库。

我在尝试加载数据时遇到了一个奇怪的错误。查询我的团队时,League属性为null。但是,如果我查询我的联赛,然后查询我的团队,联盟属性加载就好了。是什么导致了这个问题,我该如何解决?

P.S。我试过删除虚拟密钥工作(延迟加载)没有运气

方法

b.to_csv(filename, encoding="utf-8")

模型

public async Task<IActionResult> GetTeam(){
    var x = await context.Teams.ToListAsync(); 
    // var y = await context.Leagues.ToListAsync(); Leagues show up with this 
    return Json(x);
}

上下文

public class League {
    public int LeagueID { get; set; }
    public string LeagueName { get; set; }
    public virtual ICollection<Team> Teams { get; set; }
    public League() {
        Teams = new List<Team>();
    }

}

public class Team{
    public int TeamID { get; set; }
    public string TeamName { get; set; }
    public int LeagueID { get; set; }
    [ForeignKey("LeagueID")]
    public virtual League League { get; set; }
    public Team() {}
}

调试

没有Y

enter image description here

与Y

enter image description here

1 个答案:

答案 0 :(得分:1)

context.Teams.Include(t=>t.League).ToListAsync()

会一直让你成为联盟。 您必须为此工作添加using System.Data.Entity;