如何在 Entity Framework 核心优先代码方法中填充依赖实体中的外键?

How to populate a foreign key in dependent entity in Entity Framework Core first code approach?

我在 EF Core 中使用代码优先。

现在我想要国家和城市之间的 1-M 关系,即每个国家可以有很多城市,所以我这样做了。

public class Countries
{
    [Key]
    public int CountryID { get; set; }
    public string CountryName { get; set; }
}

public class Cities
{
    [Key]
    public int CityID { get; set; }
    public string CityName { get; set; }

    public Countries Countries { get; set; }

    //public List<Donor> Donors { get; set; }
}

但是在城市中填充种子数据时我不得不面对这个:

modelBuilder.Entity<Cities>().HasData(
                    new Cities { CityID= 1, CityName= "Abu Dhabi" ,  },
                     new Cities { CityID = 2, CityName = "Dubai"  ,  },
                      new Cities { CityID = 3, CityName = "Al-Ain", },
                       new Cities { CityID = 4, CityName = "Mussafah", },
                        new Cities { CityID = 5, CityName = "Shahama", }
                );

现在我不明白如何在其中填充 FOREIGN KEY 国家/地区?

你必须修复 类:

public class City
    {
        [Key]
        public int Id { get; set; }
        public string Name { get; set; }

       public int CountryId{ get; set; }

        [ForeignKey(nameof(CountryId))]
        [InverseProperty("Cities")]
        public virtual Country Country{ get; set; }

    }
public class Country
    {
        [Key]
        public int Id { get; set; }
        public string Name { get; set; }

        [InverseProperty(nameof(City.Country))]
        public virtual ICollection<City> Cities { get; set; }

    }

然后就可以初始化了

modelBuilder.Entity<Country>().HasData(
                    new Country { Id= 1, Name= "jkkl"}
);

modelBuilder.Entity<City>().HasData(
                    new City { ID= 1, Name= "Abu Dhabi" ,  CountryId=1 },
                     new City { ID = 2, Name = "Dubai", CountryId=1  },
                      new City{ID = 3, Name = "Al-Ain", CountryId=1 },
                       new City { ID = 4, Name = "Mussafah",CountryId=1  },
                        new City { ID = 5, Name = "Shahama",CountryId=1  }
                );

如果您像 Sergey 显示的那样创建 类,Country.Id 和 City.Id 将被定义为 int identity(1,1) 主键,而 City.CountryId 将是按照惯例定义为引用 Country.Id 的外键。当您保存新创建的域对象时,您无需担心键值。 EF 会为您搞定这一切。

// No need to specify Id value, the db context takes care of that.
Country UK = new Country { Name = "United Kingdom" };

// No need to specify Id or Country Id values, the db context 
// takes care of that.
UK.Cities.Add(new City { Name = "London" });
UK.Cities.Add(new City { Name = "Manchester" });
UK.Cities.Add(new City { Name = "Liverpool" });

using(YourDbContext ctx = new YourDbContext()) {

    ctx.Countries.Add(UK);

    ctx.SaveChanges();

    // After you save the changes, the db context will update 
    // the domain objects' key values (the country's Id value, and the three 
    // cities' Id and CountryId values) automatically.    
}