国家、地区、城市的数据建模

本文关键字:数据 建模 城市 地区 国家 | 更新日期: 2023-09-27 18:27:32

我想创建一个数据结构,以便在我的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;
}**

我最初的想法,但我认为这不是一个真正好的设计,因为一个位置可以有两个相同的行,在那里保持对位置的唯一引用应该是理想的

你认为良好的设计和性能如何?

国家、地区、城市的数据建模

我想这是每个人的噩梦。好至少那是我设计其中一个应用程序时的噩梦。

根据您的secenario,您可能会将国家、城市、地区作为不同的实体。所有的东西都是用这种方法找到的,直到你想让用户选择国家、地区或城市。看起来您需要有可为null的字段,这实际上不是最佳实践,因为您必须完全依赖应用程序逻辑来维护数据完整性。

这种方法的例子是:

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的角度来看,这将是一个可以为null的字段,它可能会添加脏数据(如果您不热衷于拥有整洁的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的映射。

希望这将是有用的