.net Entity Framework 中的导航属性有什么用?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1262307/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What are Navigation Properties in Entity Framework for?
提问by chobo2
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.
我在我的 EF 图中看到了很多这些导航属性,但不确定它们的真正用途。就像我在很多表中看到的那样,我有 aspnet_Users 属性。
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.
回答by marc_s
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 NOTload those navigation properties automatically for you.
如果要加载使用LINQ到实体的用户,同时也看看它的“角色”导航属性,你必须明确地包含了“角色”的实体在你的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;
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).
它基本上是一个编程等价于数据库中的外键关系 - 两个对象之间的连接。它基本上“隐藏”或解析两个表(或两个实体,在 EF 中)之间的连接。
Marc
马克

