Entity Framework 中的导航属性有什么用? [英] What are Navigation Properties in Entity Framework for?

查看:30
本文介绍了Entity Framework 中的导航属性有什么用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

这些是干什么用的?他们对加入有帮助吗?还是什么?

What are these for? Do they help for joins? or what?

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.

推荐答案

导航属性允许您从一个实体导航到已连接"实体.

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.

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

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;

或:

   // 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 中)之间的连接.

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).

马克

这篇关于Entity Framework 中的导航属性有什么用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆