实体框架 - 外键理解

时间:2018-01-15 11:27:30

标签: asp.net entity-framework rest

无法找到完整描述的教程,所以我在这里尝试。 我在VS 2017工作,我有3张桌子。 主要的一个,ParkDB:

[Table("Parking")]
    public class ParkDB
    {
        [Key]
        [Column("ParkID")]
        public int Id { get; set; }
        [Required]
        public string ParkStartDate { get; set; }
        [Required]
        public string ParkEndDate { get; set; }
        [Required]
        [ForeignKey("CityID")]
        public int ParkCityID { get; set; }
        [Required]
        [ForeignKey("StreetID")]
        public int ParkStreetID { get; set; }

    }

CitiesDB:

   [Table("Cities")]
    public class CitiesDB
    {
        [Key]
        public int CityID {  get; set; }

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


    }

街道表:

  [Table("Streets")]
    public class StreetsDB
    {

        [Key]
        public int StreetID { get; set; }
        [Required]
        [ForeignKey("CityID")]
        public int CityID { get; set; }
        [Required]
        public string StreetDesc { get; set; }

    }

我的目标是能够使用以下字段获取对象:

[ParkID,ParkStartDate,ParkEndDate] - 来自ParkDb,

[CityDesc] - 来自CitiesDB,

[StreetDesc] - 来自StreetDB,全部合并为一个Parking对象。

我正在读这篇文章:LINK

但我完全不确定什么对我有用。 此外,任何关于如何进行实际调用/查询的文章的链接都将受到赞赏..似乎无法找到有用的东西。

谢谢!

1 个答案:

答案 0 :(得分:1)

您希望应用导航属性,并且您配置的数据注释无效。我修改了这样的实体;

[Table("Parking")]
public class ParkDB
{
    [Key]
    [Column("ParkID")]
    public int Id { get; set; }
    [Required]
    public string ParkStartDate { get; set; }
    [Required]
    public string ParkEndDate { get; set; }
    [Required]
    public int ParkCityID { get; set; }

    [ForeignKey("ParkCityID")]
    public virtual CitiesDB City { get; set; }
}
[Table("Cities")]
public class CitiesDB
{
    [Key]
    public int CityID { get; set; }
    [Required]
    public string CityDesc { get; set; }

    public virtual ICollection<StreetsDB> Streets { get; set; }

    public virtual ICollection<ParkDB> Parks { get; set; }
}
[Table("Streets")]
public class StreetsDB
{
    [Key]
    public int StreetID { get; set; }
    [Required]
    public int CityID { get; set; }
    [Required]
    public string StreetDesc { get; set; }

    [ForeignKey("CityID")]
    public virtual CitiesDB City { get; set; }

}

我配置了ForeignKey个属性,并从ParkStreetID实体中删除ParkDB,因为您应该在City属性上导航它。 CitiesDB实体是中央实体,在这种情况下由其他实体协调。

最后,我提供了一些导航示例以提供更好的理解;

ParkDBs.Select(x => x.City);//Get City by ParkDBs

CitiesDBs.SelectMany(x => x.Parks);//Get Parks by CitiesDB
CitiesDBs.SelectMany(x => x.Streets);//Get Streets by CitiesDB

StreetsDBs.Select(x => x.City);//Get City by StreetsDBs
StreetsDBs.SelectMany(x => x.City.Parks);//Get Parks of City which is assosicated with StreetsDB entity