我一直在与这场斗争太久了。
我有两个共享多对多关系的模型。模型是:
public class User
{
public int UserId { get; set; }
public string UserName {get; set;}
public virtual ICollection<Role> Roles { get; set; }
}
public class Role
{
public int RoleId {get; set;}
public string RoleName { get; set; }
public virtual ICollection<User> Users { get; set; }
}
他们的关系定义如下:
public UserConfiguration()
{
HasMany(e => e.Roles)
.WithMany(i => i.Users)
.Map(t => t.MapLeftKey("UserId").MapRightKey("RoleId")
.ToTable("User_Role"));
}
现在,这在整个应用程序和#34; User_Role&#34; table充满了代码,例如:user1.Roles.Add(role1);
但是,在我的Seed方法中,我在该行上获得了Null Reference Exception。我可以看到调试时User和Role都不为null。我试图跟踪堆栈跟踪,但我没有看到NRE的来源。
我的种子方法调用是这样的:
User admin1 = context.Users.Where(p => p.Username == "DOMAIN\\username").FirstOrDefault();
//Here I add all the admins to a list of User called superAdmins
Role superAdminRole = context.Roles.Where(p => p.RoleName == "SuperAdmin").FirstOrDefault();
foreach (User user in superAdmins)
{
if (user != null)
{
user.Roles.Add(superAdminRole); <-- this throws the exception
}
}
Seed方法有什么特定的东西会让我的User_Role表在那时无法访问吗?
答案 0 :(得分:1)
我猜它抱怨Roles
集合为空。您应该在构造函数中实例化它:
public class User
{
public User()
{
// instantiate navigation property
this.Roles = new List<Role>();
}
public int UserId { get; set; }
public string UserName {get; set;}
public virtual ICollection<Role> Roles { get; set; }
}
public class Role
{
public Role()
{
// instantiate navigation property
this.Users= new List<User>();
}
public int RoleId {get; set;}
public string RoleName { get; set; }
public virtual ICollection<User> Users { get; set; }
}