2011-09-19 55 views
1

在我的數據庫我有表tblCountry和tblCity建模。它們是1:N關係。在我的域名項目中,我通過城市和國家班級代表他們。我真的需要CountryId在城市類還是隻是Country對象?
城市類:這是我應該怎麼域類

public class City 
{ 
    public int CityId {get;set;} 
    public string Name {get;set;} 
    public double Longitude {get;set;} 
    public double Latitude {get;set;} 

    // This confuse me... is this modeled fine? 
    public int CountryId {get;set;} 
    public Country Country {get;set;} 
} 

國家類

public class Country 
{ 
    public int CountryId {get;set;} 
    public string Name {get;set;} 
    public IEnumerable<City> Cities {get;set;} 
} 

我填充城市對象是這樣的:

... 
    City myCity = GetCityByCityId(cityId); 
    myCity.Country = GetCountryByCountryId(myCity.CountryId); 

    return myCity; 
... 

回答

1

我真的需要CountryId在城市類還是隻是Country對象?

的域之間的關係是「市地處國家」。代碼應儘可能基於域。您市級則要國家對象的引用:

class City { 
    private Country _country; 
} 

你不應該有CountryId在城市,因爲它是一個持久性的技術性。它應該由您的數據訪問層(ORM)處理。

+0

我以爲我的領域類應該像我的數據庫表一樣(1:1)。但現在我看到他們不應該。 – 1110

0

我更喜歡以下內容:

public class City 
{ 
    public int CityId {get;set;} 
    public string Name {get;set;} 
    public double Longitude {get;set;} 
    public double Latitude {get;set;} 


    public int CountryId {get;set;} 
    public Country Country {get;set;} 
public void LoadCountryFromDB() 
{ 
     this.Country = GetCountryByCountryId(this.CountryId); 

} 
} 

有很多數據層生成工具和模型和代碼生成的: CSLAGenMyGeneration是ORM工具(對象關係映射)中的一個。 嘗試尋找他們。

1

在這種情況下,國家是一個聚合根,它應該包含的所有城市被填充,那麼你可以簡單地得到你想要的國家,並找到聚合根內的城市。

public class City 
{ 
    public int Id {get;set;} 
    public string Name {get;set;} 
    public double Longitude {get;set;} 
    public double Latitude {get;set;} 

    public City(Country country) 
    { this.Country = country; } 
} 

public class Country 
{ 
    public int Id {get;set;} 
    public string Name {get;set;} 
    public IEnumerable<City> Cities {get;set;} 
} 

...

Country myCountry = repository.GetCountryByID(xyz); // return a country with all cities filled 

    City myCity = myCountry.Cities.First(c => c.Id = cityId); 

    return myCity; 

...

根據設計,如果紐約市是聚合根那麼設計將是

public class City 
{ 
    public int Id {get;set;} 
    public string Name {get;set;} 
    public double Longitude {get;set;} 
    public double Latitude {get;set;} 
    public Country Country {get;set;} 
} 

public class Country 
{ 
    public int Id {get;set;} 
    public string Name {get;set;} 
} 

...

City myCity = repository.GetCityByID(xyz); // return a city with the associated country 

    Country myCountry = myCity.Country; 

    return myCity; 

...