Запись в базу данных ms sql с помощью Entity Framework
У меня есть три связанных таблицы с описанными сущностями:
public class Country
{
public int CountryId { get; set; }
public string Name { get; set; }
public string CountryCode { get; set; }
public City CapitalId { get; set; }
public float CountryArea { get; set; }
public decimal Population { get; set; }
public Region RegionId { get; set; }
public virtual ICollection<City> Capital { get; set; }
public virtual ICollection<Region> Region { get; set; }
}
public class Region
{
public int RegionID { get; set; }
public string RegionName { get; set; }
}
public class City
{
public int CityID { get; set; }
public string CityName { get; set; }
}
Вот таким образом я записываю информацию в бд
using (var context = new LocalDbContext())
{
{
foreach (CountryInfo countryInfo in countryList)
{
context.Countries.Add(new Country { Name = countryInfo.Name,
CountryCode = countryInfo.NumericCode, CountryArea =
countryInfo.Area, Population = countryInfo.Population, });
context.Regions.Add(new Region() { RegionName = countryInfo.Region });
context.Cities.Add(new City() { CityName = countryInfo.Capital });
}
context.SaveChanges();
}
}
Но при этом я не понимаю, как мне в столбцы "RegionId" "CapitalID" таблицы "Country" записать информацию из соответствующих таблиц
Ответы (1 шт):
Автор решения: xxramm
→ Ссылка
Как пример
public class Country
{
[Key]
public int CountryId { get; set; }
public string Name { get; set; }
public string CountryCode { get; set; }
public float CountryArea { get; set; }
public decimal Population { get; set; }
public virtual ICollection<Region> Region { get; set; }
}
public class Region
{
[Key]
public int RegionID { get; set; }
public string RegionName { get; set; }
public int CountryID{get; set;}//foreing key
public Country Country { get; set;}
}
В EF Core существует понятие Lazy load(ленивая загрузка). Например:
var country = new Country {Name = "aaa", CountryCode = "bbb", CountryArea = 0, Population = 0};
var region = new Region {RegionName = "ccc"};
var regions = new List<Region>();
regions.Add(region);
country.Region = regions;
//При добавлении Country добавится и связанные сущности regions
_db.Countries.Add(country);
_db.SaveChanges();