Reputation: 556
I have an IQueryable<Model>
of objects in my db. I need to cast them to IQueryable<ViewModel>
class Model
{
public Guid ModelId { get; set; }
// some properties
public virtual User Users{ get; set; }
}
class User
{
public Guid UserId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
class ViewModel
{
public Guid ModelId { get; set }
public string UsersName { get; set; }
}
ViewModel.UsersName should be merged string of all users first and last names. This need to be a IQueryable since I'll use DevExpress Mvc Grid and I'll need to pass it in this way. Grid handles the paging, so it needs to IQueryable.
I've tried:
IQueryable<ViewModel> viewModel = model.Select(s => new ViewModel()
{
UsersName = s.Users
.OrderBy(d => d.LastName)
.ThenBy(d => d.FirstName)
.Aggregate(string.Empty, (s1, users) => users.FirstName + ' ' + users.Surname + ", ")
});
but it's not translatable to linq to entities. I've also tried string.join() but it won't work neither.
The result string should be for expample : "Cecelia Leblanc, Sarah Hodge" ... etc.
Thanks for any input.
Upvotes: 0
Views: 571
Reputation: 109118
Usually view models/DTOs should not be too smart, but this is a case where a little bit of smartness comes in too handy for comfort. Create a view model like:
class ViewModel
{
public Guid ModelId { get; set; }
public IEnumerable<string> UserNames { get; set; }
public string UserNamesString
{
get { return string.Join(", ", this.UserNames); }
}
}
populate it by
var models = s.Models.Select(m => new ViewModel
{ ModelId = m.ModelId,
UserNames = m.Users
.OrderBy(d => d.LastName)
.ThenBy(d => d.FirstName)
.Select(u => u.FirstName + ' '
+ u.Surname)
}).ToList();
and access the UserNamesString
property from models.AsQueryable()
.
Upvotes: 2