2017-09-14 93 views
0

有沒有簡化這個查詢的機會?我正在使用實體框架,當他們看到這個DRY違規時,我的眼睛在哭泣。數據庫有幾個典型的論壇項目表:用戶,發佈,主題,類別 - 在所有這些表都是適當的導航屬性。用GroupBy方法簡化LINQ查詢

GetMostActiveTopicByUserID返回特定用戶最活躍的主題(最活躍=所有用戶主題發送的帖子最多)。

ActiveTopicDTO GetMostActiveTopicByUserID(int id) 
{ 
    var result = _databaseContext.Users.Where(q => q.ID == id) 
    .Select(user => new UserMostActiveTopicDTO() 
    { 
     TopicName = user.Posts.GroupBy(post => post.Topic.ID) 
        .OrderByDescending(post => post.Count()) 
        .FirstOrDefault() 
        .FirstOrDefault() 
        .Topic.Name, 

     TopicAlias = user.Posts.GroupBy(post => post.Topic.ID) 
        .OrderByDescending(post => post.Count()) 
        .FirstOrDefault() 
        .FirstOrDefault() 
        .Topic.Alias, 

     TopicCategoryDescription = user.Posts.GroupBy(post => post.Topic.ID) 
        .OrderByDescending(post => post.Count()) 
        .FirstOrDefault() 
        .FirstOrDefault() 
        .Topic.Description 

     //and so on... 
    }).Single(); 

    return result; 
} 
+0

你爲什麼叫'FirstOrDefault()。FirstOrDefault()'? – maccettura

+0

爲什麼不把整個'user.Posts.GroupBy(後=> post.Topic.ID) .OrderByDescending(後=> post.Count()) .FirstOrDefault() .FirstOrDefault() .Topic'部分在一個方法裏面?然後執行'TopicName = NewMethod()。Name','TopicAlias = NewMethod().Alias'等。 – Sach

+0

@maccettura:因爲GroupBy返回IEnumerable > - 我想從第一個最大的組獲得第一個元素。這相當於針對特定用戶的帖子數量最多的主題。有點奇怪,但我不知道如何寫得更乾淨。 – user132435465

回答

1

你完整的分組是基於Topic.ID,那麼你不需要一次又一次的組合。請做一組和下面一樣返回結果,

CHANGE_TYPE_TO_TYPE_OF_RETURN-TYPE GetMostActiveTopicByUserID(int id) 
{ 
    return _databaseContext.Users 
     .Where(q => q.ID == id) 
     .Select(user => 
     { 
      user.Posts.GroupBy(post => post.Topic.ID) 
       .OrderByDescending(post => post.Count()) 
       .FirstOrDefault() 
     }) 
     .Single(); 
} 

然後從返回的結果就可以構造你的對象

+0

這正是我想要的。謝謝。 – user132435465