J
Jakob Lithner
I have three tables in my database: Person, Role and PersonRole where
PersonRole is a many-to-many relation to set roles for each person.
The tables have integer primary keys named PersonID and RoleID.
Now I want to load a checkboxlist for a specific person with all roles
visible and relevant roles checked.
To do that I tried the following code in Linq:
var personRoles = dc.PersonRoles.Where(pr => pr.PersonID == personID);
var allRoles = from r in dc.Roles
join pr in personRoles on r.RoleID equals pr.RoleID into roleGroup
from g in roleGroup.DefaultIfEmpty()
select new { g.RoleID, g.Role.RoleName, Selected = g.PersonID != 0 };
return allRoles.ToList();
The code compiles fine but in runtime produces an InvalidOperationException:
The null value cannot be assigned to a member with type System.Int32 which is
a non-nullable value type.
1) Why is that?
I feel I am pretty close but something must be wrong.
2) Could I condense the code even more by filtering on personID in the last
query? I tried that but never succeeded.
PersonRole is a many-to-many relation to set roles for each person.
The tables have integer primary keys named PersonID and RoleID.
Now I want to load a checkboxlist for a specific person with all roles
visible and relevant roles checked.
To do that I tried the following code in Linq:
var personRoles = dc.PersonRoles.Where(pr => pr.PersonID == personID);
var allRoles = from r in dc.Roles
join pr in personRoles on r.RoleID equals pr.RoleID into roleGroup
from g in roleGroup.DefaultIfEmpty()
select new { g.RoleID, g.Role.RoleName, Selected = g.PersonID != 0 };
return allRoles.ToList();
The code compiles fine but in runtime produces an InvalidOperationException:
The null value cannot be assigned to a member with type System.Int32 which is
a non-nullable value type.
1) Why is that?
I feel I am pretty close but something must be wrong.
2) Could I condense the code even more by filtering on personID in the last
query? I tried that but never succeeded.