views:

21

answers:

2

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.

A: 

Find the association between User and Role in the Model Browser, then make sure that the Role property is defined as a Navigation Property.

AJ
http://cl.ly/a9c088698369a54fc770
Jimmy
I don't see `RoleId` defined in your Users table. Does it exist in the underlying database? Is this POCO or defined using the modeler?
AJ
POCO? See my edit for more details, RoleID exists in the underlying DB, not sure why it wasn't added to the display.
Jimmy
+1  A: 

You need to load any references manually like:

Users.Roles.Load()

Added bonus:

Get out the generic repository ... awesome.

Martin