在CodeFirst中正确分割SQL数据库的代码
本文关键字:SQL 数据库 代码 分割 CodeFirst | 更新日期: 2024-10-23 17:53:18
我在EntityFramework6项目中的数据库设计遇到了一个小问题。这是我用来创建数据库的两个代码优先类。正如你所看到的,Details类违反了所有的普通形式,我想正确地拆分它,但我不知道如何正确地拆分,因为我对SQLServer和EF完全陌生。那么,获得一个像样的数据库设计的最佳方法是什么,然后我可以查询它呢?
internal class LocationDataContract
{
[Key]
public Guid Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public DbGeography Coordinates { get; set; }
public LocationsDetailsDataContract Details { get; set; }
}
internal class LocationDetailsDataContract
{
[Key, ForeignKey("Location")]
public Guid Id { get; set; }
public string Planet { get; set; }
public bool? IsCapital { get; set; }
public int Population { get; set; }
public string System { get; set; }
public string Sector { get; set; }
public LocationDataContract Location { get; set; }
}
更新了下面的问题
因此,按照乔治的建议,我做了以下事情。这会是一个不错的解决方案吗。我必须补充一点,我需要进行一些转换,因为应用程序使用不同的(完全基于继承的)模型,我必须使用这些模型,因为数据库不是唯一的数据源,并且所述数据使用另一种格式来存储我无法更改的数据。
internal class LocationDataContract
{
[Key]
public Guid Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public DbGeography Coordinates { get; set; }
public LocationsDetails Details { get; set; }
}
internal abstract class LocationDetailDataContract
{
[Key, ForeignKey("Location")]
public Guid Id { get; set; }}
public LocationsDetails Details { get; set; }
}
internal class CityDetailDataContract : LocationDetailDataContract
{
public string Planet { get; set; }
public bool? IsCapital { get; set; }
public int Population { get; set; }
}
internal class PlantDetailDataContract : LocationDetailDataContract
{
public int Population { get; set; }
public string System { get; set; }
}
internal class SystemDetailDataContract : LocationDetailDataContract
{
public string Sector { get; set; }
}
internal class SectorDetailDataContract : LocationDetailDataContract
{
// For now nothing
}
@Ruhrpottpatriot,为什么所有classe都继承自LocationDetailDataContract?这样做,我相信你会有一堆类和表,但数据将保持非标准化(例如:CityDetailDataContract将有带有重复字符串的Planet列。
你被允许从你最初的问题中做这样的事情吗?
internal class LocationDataContract
{
[Key]
public Guid Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public DbGeography Coordinates { get; set; }
public LocationDetailsDataContract Details { get; set; }
}
internal class LocationDetailsDataContract
{
[Key, ForeignKey("Location")]
public Guid Id { get; set; }
public Planet Planet { get; set; }
public System System { get; set; }
public Sector Sector { get; set; }
[Required]
public LocationDataContract Location { get; set; }
}
internal class Planet {
[Key]
public Guid Id { get; set; }
public string Name { get; set; }
public bool? IsCapital { get; set; }
public int Population { get; set; }
}
internal class System {
[Key]
public Guid Id { get; set; }
public string Name { get; set; }
}
internal class Sector {
[Key]
public Guid Id { get; set; }
public string Name { get; set; }
}