Turkdogan Tasdelen
Turkdogan Tasdelen

Reputation: 898

Order by Collection entity property in ASP.NET MVC 3 (entity framework)

I have two entities like:

public class Employee
{
    public int Id { get; set; }

    public string Name { get; set; }
    public string Lastname { get; set; }

    public virtual ICollection<EmployeeEducation> EducationList { get; set; }
}

and

public class EmployeeEducation
{
    public int Id { get; set; }

    public int EmployeeId { get; set; }

    public int Type { get; set; }

    [ForeignKey("EmployeeId")]
    public virtual Employee Employee { get; set; }

}

My question is, how can I get a specific employee and this employee's education list ordered by Type property?

I have tried:

Employee employee = _work.EmployeeRepository.GetSet()
    .SelectMany(e => e.EducationList, (e,d) => new { e, d })
        .OrderBy(x => x.d.Type)
        .Select(x => x.e)
   .FirstOrDefault(e => e.Id == id);

But it does't seem to be sorting. What is the correct way to do this?

Thanks for everyone...

Upvotes: 0

Views: 1069

Answers (2)

Gert Arnold
Gert Arnold

Reputation: 109185

You do SelectMany(), but never use the produced EducationList part, becuase you do .Select(x => x.e). But couldn't life be simpler? After all, you only get 1 employee, why not sort its EducationList as soon as you need it, after having Included it, if necessary:

Employee employee = _work.EmployeeRepository.GetSet().Include("EducationList")
.FirstOrDefault(e => e.Id == id);

Upvotes: 1

rfcdejong
rfcdejong

Reputation: 2320

Depending if u are using POCO or not u should either use CreateSourceQuery() or Query() In the case of POCO something like:

Employee employee = _work.EmployeeRepository.GetSet()
    .SelectMany(e => e.EducationList, (e,d) => new { e, d })
        .Query()
        .OrderBy(x => x.d.Type)
        .Select(x => x.e)
   .FirstOrDefault(e => e.Id == id);

Upvotes: 1

Related Questions