Question

I've been battling this for far too long.

I have 2 models which share a many-to-many relationship. The models are:

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; }
}

Their relationship is defined as such:

public UserConfiguration()
{
    HasMany(e => e.Roles)
    .WithMany(i => i.Users)
    .Map(t => t.MapLeftKey("UserId").MapRightKey("RoleId")
    .ToTable("User_Role"));
}

Now this works well all over the application and "User_Role" table gets filled with code such as: user1.Roles.Add(role1);

However, in my Seed method I get a Null Reference Exception on that line. I can see when debugging that both the User and the Role are NOT null. I tried to follow the stack trace but I failed to see where the NRE originates.

My seed method call is like this:

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

    }

}

Is there anything specific to the Seed method which would make my User_Role table inaccessible at that point?

Was it helpful?

Solution

I'm guessing that it's complaining that the Roles collection is null. You should be instantiating this in your constructors:

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; }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top