我正在使用 EF 将数据添加到数据库中,但是我是否需要实施唯一性检查,还是称它为防止多余记录的保护会更容易?
添加数据时,有必要在表中已经存在的city name
中检查我要记录的值cities
的存在,如果没有匹配项,请记录,否则,从表中获取一个现有的标识符,并与其他表实现类似。任何人都可以提供必要信息的链接,或建议如何实施该信息吗?
using (var context = new LocalDbContext())
{
foreach (CountryInfo countryInfo in countryList)
{
Region region = new Region { RegionName = countryInfo.Region};
City city = new City { CityName = countryInfo.Capital };
context.Countries.Add(new Country { Name = countryInfo.Name,
CountryCode = countryInfo.NumericCode, CountryArea = countryInfo.Area,
Population = countryInfo.Population, RegionId = region, CapitalId =
city });
}
context.SaveChanges();
}