简体   繁体   English

多对多关系的扩展方法语法

[英]Extension methods syntax for many to many relationship

Bit of Linq method syntax from a newbie here, so I appreciate any insights anyone can pass along. 这里有新手介绍的Linq方法语法,所以,我感谢任何人都可以传递的任何见解。 What I need seems simple, but it's running me around in circles. 我需要的东西似乎很简单,但是却使我无所适从。 I have 2 tables and an association (basically a junction table with only 2 fields). 我有2个表和一个关联(基本上是只有2个字段的联结表)。 I've gone through numerous posts on SO, but I'm just not getting it. 我已经阅读了很多关于SO的文章,但我只是没有理解。 Frustrating. 令人沮丧 Ok, using EF4, I have Reports and Roles and a navigation property on Reports called Roles which is the junction table (with ReportId and RoleId fields, both integer fields). 好的,使用EF4,我有“报告和角色”,以及在报告上的名为“角色”的导航属性,该属性是联结表(带有ReportId和RoleId字段,均为整数字段)。 I use a UserId to get all associated roles from the Roles table, use those roles to get the associated reports from the junction table and then get the names of the reports from Reports. 我使用UserId从Roles表中获取所有关联的角色,使用这些角色从联结表中获取关联的报告,然后从Reports中获取报告的名称。

I've tried LinqPad, but what it produces in lambda method syntax won't even work when I paste it back into LinqPad. 我已经尝试过LinqPad,但是当我将其粘贴回LinqPad时,它在lambda方法语法中产生的结果甚至不起作用。

SQL query: SQL查询:

select Reports.ReportName 
 from Reports 
 inner join UserRoles on Reports.ReportId = UserRoles.ReportId 
 inner join Roles on Roles.RoleId = UserRoles.RoleId 
 where UserRoles.UserId == userId

Code so far: 到目前为止的代码:

Reports.Select(a => a.Roles.Where(t => t.UserRoles.Select(u => u.UserId == userId)));

You can give this a shot, you may also want to filter down your select based on your needs: 您可以试一下,也可以根据需要过滤选择的内容:

var result = from allReports in Reports
             join userRoles in userRoles on allReports.ReportId equals userRoles.ReportId
             join roles in Roles on userRoles.RoleId equals roles.RoleId
             where userRoles.UserId == userid
             select allReports; 

I think this query syntax is much better in this case: 我认为这种查询语法在这种情况下要好得多:

var query = from report in db.Reports
            join ur in db.UserRoles on report.ReportId equals ur.ReportId
            join role in db.Roles on ur.RoleId equals role.RoleId
            where ur.UserId == userId
            select report.ReportName;

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

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