【问题标题】:What are Navigation Properties in Entity Framework for?实体框架中的导航属性有什么用?
【发布时间】:2009-08-11 19:03:10
【问题描述】:

我在我的 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.

【问题讨论】:

    标签: .net entity-framework


    【解决方案1】:

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

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

    编辑:

    如果您想使用 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 中的两个实体)之间的连接。

    马克

    【讨论】:

    • 啊,我在添加一些字段时遇到问题。就像我有一个表(我们称之为 tableA)表 A 有 2 个字段(字段 1 和字段 2)。我的 aspnet_userTable 具有所有标准的 asp.net 成员字段以及字段 1 和字段 2。当我尝试将新用户添加到 aspnet_userTable 时,我看不到 Field1 或 Field2。因此,我尝试分两步执行此操作,首先执行 aspnet_Users.Createaspnet_Users(),然后将其存储在 aspnet_Users 表中(我们称之为用户)。然后我尝试了 user.Field1 = "something" 这行得通。然后我尝试了 user.Field2(没有找到属性)。我看到它有这个
    • user.TableA.Field1 和 user.TableA.Field2 但是当我尝试设置它时,我只是得到一些空引用错误。我做错了什么?
    • 好吧,你的关联错了——如果你在系统中添加一个新表“TableA”,并创建一个与“aspnet_user”的外键关系,那么你的“TableA”对象就会有一个关系(导航属性)到“aspnet_User” - 而不是相反。所以在你的“TableA”实体中,应该有一个“aspnet_User”导航属性。
    • TableA 有这个。而aspnet_User有一个属性TableA(TableA)有一个0..1到many(aspnet_User)
    • 我会假设您得到空引用异常,因为 EF 不会像我在编辑的帖子中解释的那样自动加载引用的实体。您需要在代码中明确加载这些内容。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-29
    • 2016-05-29
    相关资源
    最近更新 更多