LINQ菜鸟,我该如何编写这个常见的查询?

发布于 2024-12-10 10:52:24 字数 765 浏览 0 评论 0原文

我是一名长期开发人员,但对 LINQ 仍然很陌生。当处理一组对象时,我没问题,但是当我需要从多个来源获取数据时,事情会变得更加困难,并且我可以使用一些指导来获取我需要的东西。

我的数据库中有三个表,两个相关的表和一个保存 PK/FK 将它们连接在一起的表。例如:

Users

  • UserID
  • UserName

Surveys

  • SurveyID
  • SurveyName

UserSurveys

  • UserID
  • SurveyID

我正在使用EF,所以所有这些数据已被拉入对象中。

所以...我想要做的是返回与给定用户关联的所有调查的列表。所以类似(伪代码):

// currentUserID = the UserID I need to get matching Surveys for
var surveys = from Survey where (s => s.SurveyID == UserSurvey.SurveyID && UserSurvey.UserID == currentUserID);

我假设我需要进行子查询并使用 Contains() 或类似的东西,但我一直被自己绊倒。帮助?

I'm a long time dev, but still kind of new to LINQ. I'm OK when dealing with one set of object, but things get tougher when I need to pull from several sources, and I could use some guidance in getting what I need here.

I have three tables in my database, two related tables and one that holds the PK/FK to tie them together. So something like:

Users

  • UserID
  • UserName

Surveys

  • SurveyID
  • SurveyName

UserSurveys

  • UserID
  • SurveyID

I am using EF and so all of this data has been pulled into Objects.

So... what I want to do is return a List of all Surveys that are associated with a given User. So something like (pseudo-code):

// currentUserID = the UserID I need to get matching Surveys for
var surveys = from Survey where (s => s.SurveyID == UserSurvey.SurveyID && UserSurvey.UserID == currentUserID);

I assume I need to make a sub-query and use a Contains() or something like that, but I keep tripping over myself. Help?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(3

邮友 2024-12-17 10:52:24

应该是这样的:

from us in UserSurveys
where us.UserId == currentUserID
join s in Surveys on us.SurveyID equals s.SurveyID
select s

Should be something like this:

from us in UserSurveys
where us.UserId == currentUserID
join s in Surveys on us.SurveyID equals s.SurveyID
select s
洛阳烟雨空心柳 2024-12-17 10:52:24

如果这是 EF,您应该能够进行 someUser.Surveys

If this is EF you should be able to do someUser.Surveys.

老旧海报 2024-12-17 10:52:24

假设你的数据库和实体模型有你所有的 FK 引用,你应该能够做这样的事情......

// currentUserID = the UserID I need to get matching Surveys for 
var surveys = from s in Survey 
              where s.User.UserID == currentUserID
              select s; 

Assuming your database and entity model has all of your FK references you should be able to do something like this....

// currentUserID = the UserID I need to get matching Surveys for 
var surveys = from s in Survey 
              where s.User.UserID == currentUserID
              select s; 
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文