如何通过外键选择对象
如果我有一个带有主键 (AccLinkID) 和外键 (aspnet_Users UserID) 的表,如何使用 Linq to Entities 选择外键指向的对象。
User myUser = _myDB.AccLinkSet.Where(user => user.LinkID == linkId).FirstOrDefault().aspnet_Users;
没有用...
有人有什么想法吗?
If I have a table with a primary key (AccLinkID) and a foreign key (aspnet_Users UserID), how can I select the object that the foreign key points to using Linq to Entities.
User myUser = _myDB.AccLinkSet.Where(user => user.LinkID == linkId).FirstOrDefault().aspnet_Users;
did not work...
anyone have any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
尝试这个:
Try this:
虽然您可以使用 Include 来解决此问题,正如其他人所建议的那样,但这不是我会这样做的方法。 相反,我会进行项目,它从不需要包含:
在这种情况下,用户会自动加载。
Although you can solve this with Include, as others have suggested, that's not how I'd do it. Instead, I'd project, which never requires Include:
In this case, the users are loaded automatically.
目前,在实体框架 1 中,您无法获得自动延迟加载,例如,如果您想从一个实体遍历到下一个实体,则需要执行
.Include("OtherEntity")
您选择在查询中包含这些实体,或者您需要在 EntityContext 上显式调用.Load("OtherEntity")
来加载该实体。这是 EF 团队的设计决定,不支持自动延迟加载,因为他们认为这太危险了; 他们想让用户清楚明白地知道他还包括/加载第二组实体。
由于广泛的需求,即将推出的 EF v4(将在 2009 年底与 .NET 4.0 一起发布)将支持自动延迟加载 - 如果您希望使用它。 您需要显式启用它,因为它默认处于关闭状态:
请参阅有关该新功能的一些文章:
For now, with Entity Framework 1, you don't get automatic delayed loading, e.g. if you want to traverse from one entity to the next, you need to either do an
.Include("OtherEntity")
on your select to include those entities in the query, or you need to explicitly call.Load("OtherEntity")
on your EntityContext to load that entity.This was a design decision by the EF team not to support automagic deferred loading, since they considered it to be too dangerous; they wanted to make it clear and obvious to the user that he is also including / loading a second set of entities.
Due to high popular demand, the upcoming EF v4 (to be released with .NET 4.0 sometime towards the end of 2009) will support the automatic delayed loading - if you wish to use it. You need to explicitly enable it since it's off by default:
See some articles on that new feature: