2010-09-28 71 views
0

以下linq語句會生成到數據庫的多次訪問,是否有方法可以在一次旅程中更改它?Linq-to-sql使用distinct生成單個SQL查詢()

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

供參考:在這個例子中鮮明是多餘的。

有一個成員,他PlayTimeSchedule之間的一個一對多的關係

我期待像下面將要生成:

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

還是我堅持創建一個視圖,如果我想它在一次旅行中完成?

編輯:以下是上述LINQ生成(我已經加入。取(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 
+0

那麼,SQL *最終會產生什麼? – 2010-09-29 00:09:54

回答

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(); 
+0

它是從'db.Members.Distinct()'中的m嗎?我在'{Id = m.Id.Distinct()',' – 2010-09-29 00:31:57

+0

'這樣做了一個錯誤,但它肯定不是很漂亮:'db.Members.Distinct()。Join(db.PlayTimeSchedules,m = > m.Id,pts => pts.MemberId,(m,pts)=> new {Id = m.Id,PlayTimeSchedules = pts.DayOfWeek})。ToList()。GroupBy(item => item.Id,items = > items.PlayTimeSchedules).Select(group => new {Id = group.Key,PlayTimeSchedules = group})。(20).ToList();' 如果我在GroupBy之前放棄ToList - 我最終會出現多次旅行。我想知道爲什麼。 – 2010-09-29 00:36:17

+0

請參閱我的編輯關於DISTINCT,但它看起來像您的查詢比我們想象的更復雜。你能彈出想要在LinqPad中執行的T-SQL,看看它告訴你什麼? – RPM1984 2010-09-29 00:37:16