How to Order Data Query in Entity Framework Table Relationships LINQ Method syntax?

433 views Asked by At

I am having a problem ordering data by table Iscinstances row Name in table relationships, the Iscinstances table is JOIN in LinkUsersToIscinstances table, below is my query for the table relationships.

The problem is that OrderBy a.LinkUsersToIscinstances.Iscinstances.Name is an error, how to fix the order query ?

var customer = await _context.Users
                            .Where(c => c.UserId  == UserId && c.LastActivityDate > date && c.IsApproved == num)
                            .Include(c => c.Profile)
                            .Include(a => a.LinkUsersToIscinstances).ThenInclude(b => b.Iscinstances)
                            .OrderBy(a => a.LinkUsersToIscinstances.Iscinstances.Name).ThenBy(c => c.LastName).ThenBy(c => c.FirstName)
                            .ToListAsync();

I am trying to order data by table row name in table relationships, I want to get the query to order them by table Iscinstances Name, table Users LastName, table Users FirstName

This are my classis table relationships

UserProfile

    public virtual ICollection<LinkUsersToIscinstance> LinkUsersToIscinstances { get; set; }
    public virtual ICollection<User> Users { get; set; }

LinkUsersToIscinstance

    public virtual UserProfile Profile { get; set; }
    public virtual Iscinstance Iscinstances { get; set; }
    public virtual User Users { get; set; }

Iscinstance

    public virtual ICollection<LinkUsersToIscinstance> LinkUsersToIscinstances { get; set; }

User

    public virtual UserProfile Profile { get; set; }
    public virtual ICollection<LinkUsersToIscinstance> LinkUsersToIscinstances { get; set; }
1

There are 1 answers

2
Svyatoslav Danyliv On BEST ANSWER

Try the following query.

var customer = await _context.Users
    .Where(c => c.UserId  == UserId && c.LastActivityDate > date && c.IsApproved == num)
    .Include(c => c.Profile)
    .Include(a => a.LinkUsersToIscinstances.OrderBy(x => x.Iscinstances.Name)).ThenInclude(b => b.Iscinstances)
    .OrderBy(c => c.LastName).ThenBy(c => c.FirstName)
    .ToListAsync();