C# 将城市添加到EF(实体框架)中的现有国家/地区
注意:EF尝试插入一个国家,然后将城市添加到其中,但我想将城市添加到现有的国家。C# 将城市添加到EF(实体框架)中的现有国家/地区,c#,entity-framework,C#,Entity Framework,注意:EF尝试插入一个国家,然后将城市添加到其中,但我想将城市添加到现有的国家。 City city = new City(); city.Country = Country.CreateCountry(CountryId); Entities.AddToCity(city); Entities.SaveChanges(); Exception = {"Cannot insert duplicate key row in object 'dbo.TBL#MadrakeTahsili' w
City city = new City();
city.Country = Country.CreateCountry(CountryId);
Entities.AddToCity(city);
Entities.SaveChanges();
Exception = {"Cannot insert duplicate key row in object 'dbo.TBL#MadrakeTahsili' with unique index 'IX#MadrakeTahsiliName'.\r\nThe statement has been terminated."}
这个代码怎么了?
我想在数据库中插入一个国家的城市。“(vs2008sp1)
这个国家已经存在。
City city = new City();
city.Country = Country.CreateCountry(CountryId);
Entities.AddToCity(city);
Entities.SaveChanges();
Exception = {"Cannot insert duplicate key row in object 'dbo.TBL#MadrakeTahsili' with unique index 'IX#MadrakeTahsiliName'.\r\nThe statement has been terminated."}
定义是
City Table(Id int,FK_Country int,name nvarchar(50))
Country Table(Id int,name nvarchar(50))
标识中城市和国家表中的标识(自动递增)
注意:EF尝试插入一个国家,然后将城市添加到其中,但我想将城市添加到存在的国家。我不知道是什么
Country.CreateCountry(CountryId)
可以,但在任何情况下,都需要通过EF上下文从数据库中获取现有国家/地区
City city = new City();
city.Country = Country.CreateCountry(CountryId);
Entities.AddToCity(city);
Entities.SaveChanges();
Exception = {"Cannot insert duplicate key row in object 'dbo.TBL#MadrakeTahsili' with unique index 'IX#MadrakeTahsiliName'.\r\nThe statement has been terminated."}
也就是说,实体框架知道您想要使用现有的国家,您需要通过dbContext“获取”它,然后将其分配给城市。这样,Country
实体将被“附加”,EF不会尝试创建新实体
反之亦然:从数据库中获取国家,并将
城市添加到国家,而不是国家
添加到城市我不知道是什么国家。创建国家(CountryId)
可以,但在任何情况下,都需要通过EF上下文从数据库中获取现有国家/地区
也就是说,实体框架知道您想要使用现有的国家,您需要通过dbContext“获取”它,然后将其分配给城市。这样,Country
实体将被“附加”,EF不会尝试创建新实体
反之亦然:从数据库中获取国家,并将城市添加到国家,而不是将国家
添加到城市
,如Sergi所述,您应该首先从上下文中检索国家,然后将新城市添加到其中
在伪代码中:
using (YourEntities context = getYourContextHere())
{
var countryEntity = context.CountryEntitySet.FirstOrDefault(country => country.id == newCityCountryId);
if (countryEntity == null)
throw new InvalidOperationException();
CityEntity newCity = createYourCityEntity();
newCity.Country = countryEntity;
context.SaveChanges();
}
像Sergi提到的那样,你应该首先从上下文中检索国家,然后将新城市添加到其中
在伪代码中:
using (YourEntities context = getYourContextHere())
{
var countryEntity = context.CountryEntitySet.FirstOrDefault(country => country.id == newCityCountryId);
if (countryEntity == null)
throw new InvalidOperationException();
CityEntity newCity = createYourCityEntity();
newCity.Country = countryEntity;
context.SaveChanges();
}
类似的东西应该可以用。你能写错误吗?你能写错误吗?