2

I have a User table which has a PrivilegeId foreign key points to a Privilege table and is the primary key there.

In Entity Framework, the VS will not generate a PrivilegeId variable under User for you. It will generate a Privilege property and PrivilegeReference property for you instead.

When I load a User, the Privilege property is null by default. That means EF does not load refered entity for you automatically. I think I may did something wrong? I cannot load Privilege separatedly because I have no info about the Privilege at that time. I guess EF should load the refered entities for me but I missed something. I need the PrivilegeId associated with my User object.

anybody can help me?

EDIT:

another answer: What are Navigation Properties in Entity Framework for?

Community
  • 1
  • 1
5YrsLaterDBA
  • 33,370
  • 43
  • 136
  • 210

1 Answers1

1

Sounds like you want the Include method.

List<User> users = context.Users.Include("Privilege").ToList();
Amy B
  • 108,202
  • 21
  • 135
  • 185
  • is there a way to get the table name programmatically instead of hard code the table name? – 5YrsLaterDBA Apr 13 '10 at 19:45
  • The method accepts a string, and it's easy to programmatically supply a string. – Amy B Apr 13 '10 at 22:58
  • If instead you want a compiler-checked technique be used instead of a compiler-opaque string, here's a link. http://blogs.msdn.com/stuartleeks/archive/2008/08/27/improving-objectquery-t-include.aspx – Amy B Apr 13 '10 at 23:01