What are Navigation Properties in Entity Framework for?

后端 未结 1 522
余生分开走
余生分开走 2020-11-27 17:46

I see in my EF diagram alot of these navigation properties but not sure what they are really for. Like I see in lots of my tables I have aspnet_Users properties.

Wha

相关标签:
1条回答
  • 2020-11-27 18:20

    A navigation property allows you to navigate from one entity to a "connected" entity.

    E.g. if your user is connected to a role, you can use the "Role" navigation to read and inspect the role associated with the user.

    EDIT:

    If you want to load the user with LINQ-to-Entities, and also look at its "Role" navigation property, you have to explicitly include the "Role" entity in your LINQ query - EF does NOT load those navigation properties automatically for you.

      // load user no. 4 from database
       User myUser = from u in Users.Include("Role")
                     where u.ID = 4
                     select u;
    
       // look at the role the user has
       string roleName = myUser.Role.Name;
    

    OR:

       // load user no. 4 from database
       User myUser = from u in Users
                     where u.ID = 4
                     select u;
    
       // check to see if RoleReference is loaded, and if not, load it
       if(!myUser.RoleReference.IsLoaded)
       {
          myUser.RoleReference.Load();
          // now, the myUser.Role navigation property should be loaded and available
       }
    
       // look at the role the user has
       string roleName = myUser.Role.Name;
    

    It's basically a programmatic equivalent to a foreign key relationship in a database - a connection between two objects. It basically "hides" or resolves a join between two tables (or two entities, in EF speak).

    Marc

    0 讨论(0)
提交回复
热议问题