2012-03-13 72 views
0

我想創建一個數據結構以便在我的MVC3應用程序中使用。該網站擁有用戶上傳的視頻,我希望能夠爲視頻設置位置,以便稍後您可以根據國家,地區或城市進行搜索。國家,地區,城市的數據建模

這些實體的建模對我來說不是一個大問題,我的問題是我應該爲我的視頻實體使用哪個類屬性。

public class Country 
{ 
int CountryId 
string CountryName 
} 

public class Region 
{ 
int RegionId 
string RegionName 
int FK_CountryId 
} 

public class City 
{ 
int CityId 
string CityName 
int FK_CountryId 
int FK_RegionId 
} 

........

public class Video 
{ 
int VideoId; 
string VideoName; 
**Location VideoLocation;** 
} 

**public class Location 
{ 
int LocationId; 
Country CountrId; 
Region RegionId; 
City CityId; 
}** 

我最初的想法,但我認爲這不是一個很好的設計,因爲你可以有2點相同的行了一個位置,在那裏應該是保持對位置的唯一參考的理想選擇

您認爲在良好的設計和性能方面如何?

+0

我會做'國家VideoLocation;'位置重複的就是你已經離開。 – Reniuz 2012-03-13 11:12:47

+0

如果我做國家VideoLocation如何按城市查詢例如? – CSharpLearning 2012-03-13 11:15:18

+0

'select * from Video where Video.VideoLocation.CountryId = selectedCity.FK_CountryId' – Reniuz 2012-03-13 11:19:32

回答

0

這是我猜想的每個人的噩夢。那麼......至少這是我設計其中一個應用程序時的噩夢。

根據你的情景,你可能會把國家,城市,地區作爲不同的實體。一切都是用這種方法找到的,直到你希望用戶選擇國家,地區或城市。看起來您需要具有空字段,這並不是最佳實踐,因爲您將不得不完全依賴應用程序邏輯來維護數據完整性。這種做法的

例子是:

public class Country 
{ 
    public string Code { get; set; } //country ID would not make sense in this approach 
    public string Name { get; set; } 
} 

public class Region 
{ 
    public string Code { get; set; } 
    public string Name { get; set; } 
    public string CountryCode { get; set; } //1 region is assigned to only 1 country 
} 

public class City 
{ 
    public string Code { get; set; } 
    public string Name { get; set; } 
    public string RegionCode { get; set; } //1 city is assigned to only 1 region 
} 

它看起來不錯,簡單易懂但想想,你捕捉什麼被選擇的表。如果你只關心城市(依賴列表中的最後一項),那一切都很清楚。

public class UserSelectionWithCityOnly 
{ 
    public string CityCode { get; set; } 
} 

很容易和直截了當?看起來是這樣。 考慮場景,你可以選擇任何一個國家,城市或區域....它得到的真的很亂:

public class UserSelectionWithEitherSelected 
{ 
    public string? CityCode { get; set; } 
    public string? RegionCode { get; set; } 
    public string? CountryCode { get; set; } 
} 

嗯......你總是可以檢查是否CityCode.HasValue,但從DB點將是一個可空場,可在其中加髒數據(如果你不是迂腐大約有乾淨整潔的DB應該是罰款)

所以他們的方式我解決,這是通過創建與父項ID一個階層表:

public class MySolutionForDestinations 
{ 
    public int DestinationId { get; set; } //primary key 
    public int ParentDestinationId { get; set; } 
    public string Code { get; set; } 
    public string Name { get; set; } 
    public DestinationLevel Level { get; set; } 
} 

public enum DestinationLevel 
{ 
    Country = 0, 
    Region = 1, 
    City = 2 
} 

它可能不是最優雅的解決方案,但它工作得很好。在這種方法中,你只關心DestinationId,它可以是一個國家ID,地區ID或城市ID,所以你肯定會避免有髒數據,並可以實現1對1映射。

希望這將是有用的

+0

謝謝,足夠清楚,以適應我自己的情況 – CSharpLearning 2012-03-13 14:12:57