EF Code first related entities context fail

泪湿孤枕 提交于 2019-12-04 11:42:20

Try to eager-load the roles by including them explicitly:

Member admin = db.Members.Include("Roles").FirstOrDefault(m => m.Name == "Admin");

Your MembersRole and Roles navigation properties are not virtual so EF can't crete proxy for lazy loading. Because of that you must explicitely ask EF to load your navigation properties. Either mark your properties as virtual:

public class Role
{
    public int Id { get; set; }
    public string Title { get; set; }

    public virtual ICollection<Member> MembersInRole { get; set; }
}

public class Member
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Password { get; set; }
    public string Email { get; set; }

    public virtual ICollection<Role> Roles { get; set; }
}

Or use @Yakimych approach. The eager loading in EF 4.1 can be also defined with lambdas:

Member admin = db.Members.Include(m => m.Roles)
                         .FirstOrDefault(m => m.Name == "Admin");
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!