I have a model like this:
Client – which has many Locations – which can have many Teams, a sort of one-to-many-to-many relationship.
I can find lots of examples of one-to-many relationships, but none like this.
The question is: how do I get back a Client object with all the Locations and the Teams for those locations?
Previously, with SQL, I would have joined all the tables which would have given me a row for each, but I can’t seem to do it, even with a ViewModel combining them 🙁
public class Client
{
private System.Guid _id;
[HiddenInput(DisplayValue = false)]
public System.Guid ClientId {
get
{
if (_id == null || _id == Guid.Empty)
_id = Guid.NewGuid();
return _id;
}
set
{
_id = value;
}
}
[Required(ErrorMessage = "The Client Name is required")]
public String Name { get; set; }
public virtual ICollection<Location> Locations { get; set; }
}
public class Location
{
private System.Guid _id;
[HiddenInput(DisplayValue = false)]
public System.Guid LocationId {
get
{
if (_id == null || _id == Guid.Empty)
_id = Guid.NewGuid();
return _id;
}
set
{
_id = value;
}
}
[Required(ErrorMessage = "The Site Name is Required")]
public String Name { get; set; }
[Required(ErrorMessage = "The Address is required")]
public String Address { get; set; }
[Required(ErrorMessage = "The Postcode is required")]
public String Postcode { get; set; }
public virtual ICollection<EngagementTeam> Teams { get; set; }
}
public class EngagementTeam
{
private System.Guid _id;
[HiddenInput(DisplayValue = false)]
public System.Guid EngagementTeamId {
get
{
if (_id == null || _id == Guid.Empty)
_id = Guid.NewGuid();
return _id;
}
set
{
_id = value;
}
}
[Required(ErrorMessage = "The Team Name is required")]
public String Name { get; set; }
public virtual ICollection<Person> Members { get; set; }
}
I think you’re confusing your data or domain model with your UI or View Model. They are not typically the same thing.
The reason is that View Models tend to be simpler, and only provide the data needed to display a particular view. This is important because view models get recreated by the model binder on every post back request, and if you ahve a very complex model then this makes it very hard for the model binder to create.
You are also thinking about your model wrong. Client has no relationship to team whatsoever. This is not a “one to many to many”, this is two relationships, both 1 to many. Client is related to location. Location is related to team. Client is not related to Team, other than through location.
So your client simply has a collection of Locations. And your Location has a collection of teams. Your Team will likely have a single reference to it’s location, and your location will have a single reference to it’s client. That’s it.