我有两个简单的课程
public class User
{
public User()
{
Roles = new Collection<Role>();
}
public int UserId { get; set; }
public string UserName { get; set; }
public ICollection<Role> Roles { get; set; }
}
public class Role
{
public Role()
{
Users = new Collection<User>();
}
public int RoleId { get; set; }
public string RoleName { get; set; }
public ICollection<User> Users { get; set; }
}
我通过覆盖种子方法用以下数据播种了它
var firstUser = new User {UserName = "vivekr"};
var secondUser = new User {UserName = "vivekm"};
var firstRole = new Role {RoleName = "admin"};
var secondRole = new Role {RoleName = "user"};
firstUser.Roles.Add(firstRole);
firstUser.Roles.Add(secondRole);
secondUser.Roles.Add(firstRole);
context.Users.Add(firstUser);
context.Users.Add(secondUser);
映射是通过重写 OnModelCreating() 来完成的
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<User>()
.HasMany<Role>(r=> r.Roles)
.WithMany(u => u.Users)
.Map(c=>
{
c.MapLeftKey("UserId");
c.MapRightKey("RoleId");
c.ToTable("UserRoles");
});
}
所有表都正确创建,我可以看到值是正确的(包括映射)
但是我在获取数据时有问题
如果我这样做(假设 db 是我的 Context 类的一个实例)
var selectedRoles = db.Users.Find(1).Roles;
我得到 selectedRoles 的计数为 0。它应该是 2。我不知道为什么会这样