Entity relationship not reading correctly from database
I have an entity relationship setup in my mvc2 application such that each user has one role and each role can have many users. Like so:
Roles Users
-------- ---------
RoleID-- UserID
\
Name --> RoleID
So a pretty basic many to one relationship enforced in the database and reflected in my entity relationship 开发者_运维百科diagram. However when I try to get the user's role (user.Role.Name
) it is always null, and I see in the database that the user's role is set to a valid ID. This is my first attempt at using entities as I had always used LINQ2SQL before and this is just baffling me.
What do?
Here's a screen shot of my edmx file
http://cl.ly/a9c088698369a54fc770
In the database the user table has a RoleID property (not sure why it isn't displaying in the diagram) and I am freely able to traverse from User to Role and it is known that it is a one to many relation to the compiler but it is just coming back as null when trying to view a user object.
EDIT:
Here's the query I use
User user = db.Users.SingleOrDefault(u => u.Username == username);
user.Role.Name
My user object isn't null and any of its other properties are visible just can't see the role, and each user has one role.
You need to load any references manually like:
Users.Roles.Load()
Added bonus:
Get out the generic repository ... awesome.
Find the association between User and Role in the Model Browser, then make sure that the Role property is defined as a Navigation Property.
精彩评论