实体框架中的导航属性是什么?

时间:2009-08-11 19:03:11

标签: .net entity-framework

我在EF图表中看到了很多这些导航属性,但不确定它们的用途。就像我在很多表中看到的那样,我有aspnet_Users属性。

这些是为了什么?他们帮助加入吗?或者什么?

Error 2
Error 3007: Problem in Mapping Fragments starting at lines 1201, 1423: 
Non-Primary-Key column(s) [Field2] are being mapped in both fragments 
to different conceptual side properties - data inconsistency is possible 
because the corresponding conceptual side properties can be independently 
modified.

1 个答案:

答案 0 :(得分:45)

导航属性允许您从一个实体导航到“已连接”实体。

E.g。如果您的用户已连接到某个角色,则可以使用“角色”导航来阅读和检查与该用户关联的角色。

编辑:

如果要使用LINQ-to-Entities加载用户,并查看其“Role”导航属性,则必须在LINQ查询中明确包含“Role”实体 - EF NOT < / strong>自动为您加载这些导航属性。

  // 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;

它基本上是一个程序化的等价于数据库中的外键关系 - 两个对象之间的连接。它基本上“隐藏”或解析两个表(或两个实体,在EF中)的连接。

马克