.net - Entity Framework 中的导航属性有什么用?

标签 .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.

最佳答案

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

例如。如果您的用户连接到某个角色,您可以使用“角色”导航来读取和检查与该用户关联的角色。

编辑:

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

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

或者:
   // 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 中)之间的连接。

马克

关于.net - Entity Framework 中的导航属性有什么用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1262307/

相关文章:

.net - 在 Windows 服务启动时等待网络配置完成

.net - 在 Visual Studio 中构建具有大量控件的 GUI

c# - EF-Code First : Unable to create a constant value of type '' . Only primitive types ('such as Int32, String, and Guid' ) are supported in this context

c# - Entity Framework 列映射

c# - 如何覆盖 WcF 对象的 ToString 方法?

c# - .NET 4.0 到 4.5 迁移并在 4.0 机器上运行异常

c# - 为什么 WeakReference.IsAlive 变为假?

sql-server-2005 - 在单个 ASP.NET 应用程序中使用 Entity Framework 的多个版本的 SQL Server

c# - SqlBulkCopy 多个表在单个事务下插入或 Entity Framework 和经典 Ado.net 之间的批量插入操作

c# - MVC 数据库迁移 : The method or operation is not implemented?