简体   繁体   English

如何在L2E或EF中使用外键?

[英]how to use Foreign key in L2E or EF?

I have a User table which has a PrivilegeId foreign key points to a Privilege table and is the primary key there. 我有一个User表,其中的PrivilegeId外键指向Privilege表,并且是那里的主键。

In Entity Framework, the VS will not generate a PrivilegeId variable under User for you. 在实体框架中,VS不会在“ User ”下为您生成PrivilegeId变量。 It will generate a Privilege property and PrivilegeReference property for you instead. 相反,它将为您生成Privilege属性和PrivilegeReference属性。

When I load a User , the Privilege property is null by default. 当我加载User ,默认情况下, Privilege属性为null That means EF does not load refered entity for you automatically. 这意味着EF不会自动为您加载引用的实体。 I think I may did something wrong? 我想我可能做错了什么? I cannot load Privilege separatedly because I have no info about the Privilege at that time. 我无法单独加载Privilege因为那时我没有有关Privilege信息。 I guess EF should load the refered entities for me but I missed something. 我想EF应该为我加载引用的实体,但我错过了一些东西。 I need the PrivilegeId associated with my User object. 我需要与User对象关联的PrivilegeId

anybody can help me? 有人可以帮助我吗?

EDIT:

another answer: What are Navigation Properties in Entity Framework for? 另一个答案: 实体框架中的导航属性有哪些用途?

听起来像您想要Include方法

List<User> users = context.Users.Include("Privilege").ToList();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM