2016-02-05 22 views
0

我遇到了實體框架的問題。我被平均值從關鍵的一個嘗試排序我的收藏:使用linq降序排列的平均值

var userPhotos = Database.Set<Photo>().Where(p => string.IsNullOrEmpty(userId) || p.ClientProfileId == userId); 
usersPhotos = usersPhotos.OrderByDescending(item => item.Votes.Average());` 

在我所「指定的類型成員的投票'在LINQ是不支持的實體代碼的最後一行只有初始化,實體成員和實體導航屬性均受支持。「執行。 我的會員投票看起來像這樣:

public class Photo : BaseEntity, IEntity<Guid> 
{ 
    public Photo() 
    { 
     Id = Guid.NewGuid(); 
     Votes = new List<double>; 
    } 
    [Key] 
    public Guid Id { get; set; } 
    //Other fields 
    public ICollection<double> Votes { get; set; } 
} 

如何解決我的問題,並通過該成員的avarege值做排序?

回答

1

所有你需要的是第一行結尾處的ToList()。

你可以這樣做;

var userPhotos = Database.Set<Photo>().Where(p => string.IsNullOrEmpty(userId) || p.ClientProfileId == userId).ToList(); 
var sortedUsersPhotos = usersPhotos.Where(p=>p.Votes!=null && p.Votes.Any()).OrderByDescending(item => item.Votes.Average()); 
+0

它創建了一個新的對象不是強制性的。這是更優雅的方式嗎? – user3818229

+0

'usersPhotos'從哪裏來? –

+0

更新了我的問題。 – user3818229

0

可以使用的GroupBy:

var sorted = userPhotos.GroupBy(item => item.Votes.Average()).OrderByDescending(item => item.Key); 

如果你想使用相同的對象:

userPhotos = userPhotos.GroupBy(item => item.Votes.Average()).OrderByDescending(item => item.Key).SelectMany(x=>x); 
+0

的答案嘗試了第二個版本,仍然是「NotSupportedExecption」 – user3818229