0

I faced a problem with entity framework. I'm trying sort my collection by average value from one of the key:

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

In the last line of code I have "The specified type member 'Votes' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported." execpetion. My member Votes looks like so:

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; }
}

How to fix my problem and make sort by avarege value of this member?

user3818229
  • 1,537
  • 2
  • 21
  • 46

2 Answers2

1

All you need to is ToList() at the end of the first line.

You can do it this way;

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());
Kosala W
  • 2,133
  • 1
  • 15
  • 20
0

You can use GroupBy:

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

If you want to use the same object:

userPhotos = userPhotos.GroupBy(item => item.Votes.Average()).OrderByDescending(item => item.Key).SelectMany(x=>x);
Tyress
  • 3,573
  • 2
  • 22
  • 45