【问题标题】:Extension methods syntax for many to many relationship多对多关系的扩展方法语法
【发布时间】:2013-01-28 05:00:51
【问题描述】:

这里是新手的一点 Linq 方法语法,所以我很感激任何人都可以传递的任何见解。我需要的东西看起来很简单,但它让我绕圈子。我有 2 个表和一个关联(基本上是一个只有 2 个字段的联结表)。我已经浏览了很多关于 SO 的帖子,但我就是不明白。令人沮丧。好的,使用 EF4,我在 Reports 上有一个名为 Roles 的导航属性,它是联结表(具有 ReportId 和 RoleId 字段,均为整数字段)。我使用 UserId 从 Roles 表中获取所有关联的角色,使用这些角色从联结表中获取关联的报告,然后从 Reports 中获取报告的名称。

我已经尝试过 LinqPad,但是当我将它粘贴回 LinqPad 时,它在 lambda 方法语法中产生的内容甚至无法正常工作。

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

到目前为止的代码:

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

【问题讨论】:

  • navigation properties配置了吗?他们可以为您做left join 的工作。
  • 是的 ..“名为 Roles 的报告上的导航属性是联结表(具有 ReportId 和 RoleId 字段,均为整数字段)”。 “a => a.Roles”部分是我尝试使用导航属性。

标签: c# linq entity-framework linq-to-entities inner-join


【解决方案1】:

您可以试一试,您可能还想根据自己的需要过滤您的选择:

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; 

【讨论】:

  • 谢谢,但我需要的是查询的方法语法。查询语法我掌握得很好,但我的大脑似乎无法将其转换为方法语法(并且当前项目对方法语法有要求)。
  • 看看这个它可能会给你一些帮助 - weblogs.asp.net/fmarguerie/archive/2009/02/06/…
【解决方案2】:

我认为这种查询语法在这种情况下要好得多:

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;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-09-28
    • 1970-01-01
    • 2010-11-16
    • 1970-01-01
    • 1970-01-01
    • 2018-01-25
    • 2019-12-30
    • 1970-01-01
    相关资源
    最近更新 更多