它是一个正确的数据库设计?

时间:2014-04-09 05:46:09

标签: c# asp.net-mvc-4 ef-code-first relational-database

我正在使用EF 5,Web Api和MVC4我需要有关此数据库设计的帮助。我需要在数据库中保存医院的城市和城镇,但没有周期,医院有一个城市和城镇,一个城市有许多城镇

public class City
{
    public int CityId { get; set; }
    public List<Town> Towns { get;  set; }
    public string Name { get; set; }
    [Timestamp]
    public byte[] RowVersion { get; set; }

    public City()
    {
        Towns = new List<Town>();
    }
}

 public class Town
{
    public int TownId { get; set; }

    public int CityId { get; set; }

    public string Name { get; set; }

    public byte[] RowVersion { get; set; }
}

 public class Hospital
{
    public int HospitalId { get; set; }

    [Required]
    public string Name { get; set; }

    public int TownId { get; set; }
    public  Town Town { get; set; }

    public int CityId { get; set; }

    public City City { get; set; }

    public bool IsAvailable { get; set; }

    [Timestamp]
    public byte[] RowVersion { get; set; }


    public Hospital()
    {
      this.IsAvailable = true;
    }
}

我不喜欢医院类的City,但我需要另一种选择,就像一个循环

3 个答案:

答案 0 :(得分:1)

&#34;周期&#34;有什么问题? EF一直使用它们,双向导航非常有用!当然,它在尝试序列化时会中断,但你不应该这样做:)。

关于你的问题,如果一个城市&#34;有&#34;多个城镇,一个医院在一个城镇,那么医院就不需要了解一个城市。它知道它所在的城镇,以及它所在的城市。当然,如果一个城镇可以在一个以上的城市,(但医院是一对独特的城市),那么你的设计看起来很完美。

根据您提供的信息,我会删除&#34; City&#34;来自医院类的财产。如果您需要访问它,只需通过Town酒店。

myHospital.Town.City

答案 1 :(得分:0)

那么,如果每个城镇都与一个城市相关,并且每个医院都与一个城镇相关,那么您可以使用这些关系轻松找到医院的城市。

您不需要将City作为数据库中Hospital表中的列,但为了简单起见,您可能仍希望将其作为代码中的属性。
在这种情况下,简单的方法是将Hospital类连接到视图而不是实际的Hospital表。

答案 2 :(得分:0)

如果我要编写该应用程序,我会接受这样的课程。

City不包含任何关系属性:

public class City
{
    public int Id { get; set; }
    public string Name { get; set; }
    [Timestamp]
    public byte[] RowVersion { get; set; }
}

Town位于任何City

public class Town
{
    public int Id { get; set; }
    public int CityId { get; set; }
    public string Name { get; set; }
    public byte[] RowVersion { get; set; }
}

Hospital位于Town。您可以City

访问TownId
public class Hospital
{
    public int Id { get; set; }
    [Required]
    public string Name { get; set; }
    public int TownId { get; set; }

    //you can uncomment this for less coding for searching, filtering etc..
    //public int CityId { get; set; }

    public bool IsAvailable { get; set; }
    [Timestamp]
    public byte[] RowVersion { get; set; }
    public Hospital()
    {
      this.IsAvailable = true;
    }
}