Reputation: 15608
I want to present an example and some requirements and want to understand what the best domain model should should.
The DB is:
One Country has Many Cities.
One City has many Towns
Both tables have Id column.
In my C#, I have
public class Country
{
public List<City> Cities {get;set;}
public int Id;
}
public class City
{
public int Id {get;set;}
public int CountryId {get;set;}
}
When I want to insert a new City, I can take city object and insert it in Db. So this design works.
When I want to delete a city, I take the Id of city and delete it from Db. So this design works.
When I want to show a city, I also need country column in the grid in UI so this design doesn't work.
I would then get country of each city from the country id column and that's painful.
If I had Country has a property of City class then I would have to create Country object for all city objects and I don't need the country object during update, insert and delete - I just need CountryId.
So my question is:
Upvotes: 2
Views: 1680
Reputation: 65456
If I had Country has a property of City class then I would have to create Country object for all city objects and I don't need the country object during update, insert and delete - I just need CountryId.
What's wrong with filling a Country
object in all the City
objects? They don 't need to be populated, you can simply store the IDs. This is known as lazy-loading in the ORM world (and possibly outside too).
For example:
public class Country
{
private List<City> _cities;
public int Id { get;set; }
public IEnumerable<City> Cities
{
get
{
// load on demand
if (_cities == null)
_cities = LoadCities(Id);
return _cities;
}
}
}
public class City
{
public int Id { get;set; }
public Country Country { get;set; }
}
It boils down to which side of the relationship is in control. Is the country responsible for updating all its children (a cascading update), or do you just want the City to do it? Either way, holding a Country object is a lot less database-centric than having IDs floating around.
If you are performing a join between the Cities and Countries table (instead of LoadCities) then you'll have each city's country id anyway, and be pre-fetching the data.
Upvotes: 1
Reputation: 47809
Why don't you just add a backreference to the Country object from City? that way, if you need the country's name you can just do:
string countryname = city.Country.Name;
This is how an ORM like entity framework would design it by default
Upvotes: 0