Trying to be more efficient with my queries, but not sure how to write this all as one query. I've got a domain model:
public class UserReport : Entity
{
public string Name { get; set; }
public List<string> Statuses { get; set; }
public List<GroupModel> Groups { get; set; }
public string Email { get; set; }
public string OfficeStates {get; set;} //Comma delimited list
}
public class GroupModel : Entity
{
public string Name {get; set;}
public string Type {get; set;
}
Which is a "compound entity", if you will. The standard entities representing those collections are M2M relational entities with the User
object:
public class User : Entity
{
public string FirstName { get; set; }
public string LastName { get; set; }
public ICollection<Status> Statuses { get; set; }
public ICollection<Group> Groups { get; set; }
public ICollection<Office> Offices { get; set; }
}
public class Office : Entity
{
//other properties
public State State { get; set; }
}
public class State : Entity
{
public string Name { get; set; }
public string Abbreviation { get; set; }
}
So far I've got:
Context.DbSet<User>.Select(user => new UserReport()
{
Name = user.FirstName + ", " + user.LastName,
Email = user.Email,
Statuses = user.Statuses.Select(status => status.Name).ToList(),
Groups = user.Groups.Select(group => new GroupModel(){ Name = group.Name, Type = group.Type.Name}).ToList(),
OfficeStates = string.Join(",", user.Offices.Select(office => office.State.Abbreviation).ToList())
}).ToList();
Which throws an error:
LINQ to Entities does not recognize the method 'System.String Join(System.String, System.Collections.Generic.IEnumerable`1[System.String])' method, and this method cannot be translated into a store expression.
I totally get what this is saying and I know if I called .ToList() before my select it would work, but I need to have this be one query, so I can still have an IQueryable to apply filtering later. Surely there must be some way in LINQ to do this. It can be done in SQL: Concatenate many rows into a single text string?, how can it be done via LINQ?