EF Code first related entities context fail
Dunno how to name this properly. I have two entities in m:n relationship: Member and Role.
public class Role
{
public int Id { get; set; }
public string Title { get; set; }
public 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 ICollection<Role> Roles { get; set; }
}
I have made some seed data:
http://i56.tinypic.com/2vjvj1w.pngAnd wrote test:
The problem is, that my Member entity has no roles assigned, even when I created them in context (as you can see at images). I don't know what's wrong. Tables in database seems to be ok. I am not sure if there isn't something 开发者_如何学编程wrong with context instances. But it should be ok, becuase I am working with seed data all the time.
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");
Try to eager-load the roles by including them explicitly:
Member admin = db.Members.Include("Roles").FirstOrDefault(m => m.Name == "Admin");
精彩评论