如何通过外键选择对象

发布于 2024-07-29 11:32:29 字数 254 浏览 3 评论 0原文

如果我有一个带有主键 (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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

零時差 2024-08-05 11:32:29

尝试这个:

User myUser = _myDB.AccLinkSet.Include("aspnet_Users")
    .Where(user => user.LinkID == linkId).FirstOrDefault().aspnet_Users;

Try this:

User myUser = _myDB.AccLinkSet.Include("aspnet_Users")
    .Where(user => user.LinkID == linkId).FirstOrDefault().aspnet_Users;
感悟人生的甜 2024-08-05 11:32:29

虽然您可以使用 Include 来解决此问题,正如其他人所建议的那样,但这不是我会这样做的方法。 相反,我会进行项目,它从不需要包含:

var q = from al in yDB.AccLinkSet
        where al.LinkID == linkId
        select al.aspnet_Users;

在这种情况下,用户会自动加载。

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:

var q = from al in yDB.AccLinkSet
        where al.LinkID == linkId
        select al.aspnet_Users;

In this case, the users are loaded automatically.

倚栏听风 2024-08-05 11:32:29

目前,在实体框架 1 中,您无法获得自动延迟加载,例如,如果您想从一个实体遍历到下一个实体,则需要执行 .Include("OtherEntity")您选择在查询中包含这些实体,或者您需要在 EntityContext 上显式调用 .Load("OtherEntity") 来加载该实体。

这是 EF 团队的设计决定,不支持自动延迟加载,因为他们认为这太危险了; 他们想让用户清楚明白地知道他还包括/加载第二组实体。

由于广泛的需求,即将推出的 EF v4(将在 2009 年底与 .NET 4.0 一起发布)将支持自动延迟加载 - 如果您希望使用它。 您需要显式启用它,因为它默认处于关闭状态:

context.ContextOptions.DeferredLoadingEnabled = true;

请参阅有关该新功能的一些文章:

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:

context.ContextOptions.DeferredLoadingEnabled = true;

See some articles on that new feature:

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文