LINQ菜鸟,我该如何编写这个常见的查询?
我是一名长期开发人员,但对 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
应该是这样的:
Should be something like this:
如果这是 EF,您应该能够进行
someUser.Surveys
。If this is EF you should be able to do
someUser.Surveys
.假设你的数据库和实体模型有你所有的 FK 引用,你应该能够做这样的事情......
Assuming your database and entity model has all of your FK references you should be able to do something like this....