Linq-to-sql生成带有distinct()的单个SQL查询

时间:2010-09-28 23:53:12

标签: sql linq-to-sql

以下linq语句生成多次访问数据库,有没有办法改变它,以便它在一次旅行中完成?

db.Members.Distinct().Select(
    m => new { 
        Id = m.Id, 
        PlayTimeSchedules = m.PlayTimeSchedules.Select(pts => pts.DayOfWeek) }
).ToList();

仅供参考:在此示例中,Distinct是多余的。

会员和他的PlayTimeSchedule之间存在一对多的关系

我希望能够生成以下内容:

select distinct(Members.Id), PlayTimeSchedule.DayOfWeek from Members 
join PlayTimeSchedule on PlayTimeSchedule.MemberId = Members.Id

或者如果我希望在一次旅行中完成它,我会不会创建一个视图?

编辑:以上是linq生成的内容(为了简洁,我添加了.Take(20)):

    SELECT TOP (20) [t1].[Id]
    FROM (
        SELECT DISTINCT [t0].[Id], [t0].[EMail], [t0].[Username], [t0].[Password], [t0].[GmtOffset], [t0].[LastSeen], [t0].[Notifications], [t0].[EMailVer
    ified], [t0].[ObserveDst], [t0].[Admin], [t0].[AttendedRaidCount], [t0].[MissedRaidCount], [t0].[LedRaidCount], [t0].[CommittedRaidCount]
        FROM [dbo].[Members] AS [t0]
        ) AS [t1]
    -- Context: SqlProvider(Sql2008) Model: AttributedMetaModel Build: 3.5.30729.1

    SELECT [t0].[DayOfWeek]
    FROM [dbo].[PlayTimeSchedule] AS [t0]
    WHERE [t0].[MemberId] = @x1
    -- @x1: Input Int (Size = 0; Prec = 0; Scale = 0) [1]
    -- Context: SqlProvider(Sql2008) Model: AttributedMetaModel Build: 3.5.30729.1

    SELECT [t0].[DayOfWeek]
    FROM [dbo].[PlayTimeSchedule] AS [t0]
    WHERE [t0].[MemberId] = @x1
    -- @x1: Input Int (Size = 0; Prec = 0; Scale = 0) [2]
    -- Context: SqlProvider(Sql2008) Model: AttributedMetaModel Build: 3.5.30729.1

    +++ 18 more DayOfWeek selections as above

1 个答案:

答案 0 :(得分:1)

.Select不会进行连接(这是您想要的),使用.Join或者如果它更容易,请使用非lambda方式:

var query = (from m in db.Members
            join s in db.PlayTimeSchedules on m.Id equals s.MemberId
            select new { Id = m.Id, PlayTimeSchedules = s.DayOfWeek }).Distinct();