Reputation: 1188
I'm trying to put together a ViewModel that will have a list of users and each user will have a list of locations. The User table and Location table are joined together through another table that holds each respective ID and some other information. This table is essentially a many to many join table. I've tried a few different viewModel approaches and they we're severely lacking... What would be the best approach for displaying this type of information?
Upvotes: 1
Views: 990
Reputation: 78850
I assume that the issue is that you want to be able to access the collection by either User or Location. One approach could be to use ILookup<>
classes. You'd start with the many-to-many collection and produce the lookups like this:
var lookupByUser = userLocations.ToLookup(ul => ul.User);
var lookupByLocation = userLocations.ToLookup(ul => ul.Location);
Update:
Per your description, it seems like you don't really need to have a full many-to-many relationship in your ViewModel. Rather, your ViewModel could have a structure like this:
public class YourViewModel
{
public IEnumerable<UserViewModel> Users { get; set; }
}
public class UserViewModel
{
// User-related stuff
public IEnumerable<LocationViewModel> Locations { get; set; }
}
If you wanted to avoid redundant LocationViewModel
objects, you could pre-build a mapping between your Model and ViewModel objects:
var locationViewModels = myLocations.ToDictionary(
loc => loc, loc => CreateLocationViewModel(loc));
And then reuse these objects when populating your page's ViewModel.
Upvotes: 2