0

I use Entity Framework and MVC. I need Address list order by address id. But when i encapsulate property my for the sort so entity framework doesn't fill address list. what can i do?

public class Student
{
    public int StudentId { get; set; }
    public string Name{ get; set; }
    public string Surname{ get; set; }

    //i need this address list order by address id???
    public virtual List<StudentAddress> Address { get; set; }
}

public class StudentAddress
{
    [Key]
    public int AddressId{ get; set; }

    public string Address { get; set; }
    public string City { get; set; }

}
Christoph Fink
  • 22,727
  • 9
  • 68
  • 113
Yargicx
  • 1,704
  • 3
  • 16
  • 36
  • Why do you care what the order of the list is in the class? If you want to display it in a particular order then order it in the UI. – Ben Robinson Nov 19 '14 at 12:57
  • because i use it alot of location. – Yargicx Nov 19 '14 at 12:59
  • 1
    Then order it whenever you need it. Also, I suspect ordering by Id is not always a good idea, what if something changes for the student and Id 2 becomes the primary address? – DavidG Nov 19 '14 at 13:00
  • you should call Include for example: db.Students.Include("Address").ToList(); or db.Students.Include(t=>t.Address).ToList(); after you add using System.Data.Entity; – Monah Nov 19 '14 at 13:20

3 Answers3

2

Relationships are considered unordered as per standard of relational modelling so you won't be able and you shouldn't rely on order, but you should apply ordering before presenting your data. So you can select anonymous type with ordered addresses like:

students.Select(x => new { Student = x, Addresses = x.Address.OrderBy(y => y.AddressId)) })

And if you worry about code duplications you can wrap that into separate method and reuse it.

Vladimirs
  • 8,232
  • 4
  • 43
  • 79
0

I am not aware of a way by doing this via EF/SQL, but you could do something like this:

protected IEnumerable<StudentAddress> addresses;
public virtual IEnumerable<StudentAddress> Address
{
    get { return addresses; }
    set
    {
        addresses = value == null ? null : value.OrderBy(a => a.AddressId);
    }
}
Christoph Fink
  • 22,727
  • 9
  • 68
  • 113
0

I'm assuming that when you said 'But when i encapsulate property my for the sort so entity framework doesn't fill address list' that Entity Framework doesn't fill the address list and that you're using lazy loading here.

You need to import System.Data.Entity in order to use .Include() that supports a lambda. After Include'ing it you can just apply an OrderBy() on the property you want sorted, like so:

DbContext.Students.Include(s => s.Address.OrderBy(a => a.AddressId))

You're probably also better off replacing the List with an IList, IQueryable or IEnumerable. If you wish to support insert operations on the address you're best off with an IList.

Toolmaker
  • 554
  • 6
  • 22