Note : EF try to Insert a Country and then add the city to it But I want to add the city to a country that exist.
City city = new City();
city.Country = Country.CreateCountry(CountryId);
Entities.AddToCity(city);
Entities.SaveChanges();
What’s wrong with this code?
I want to insert a city of for a country to database. “(vs2008sp1)”
The country already exist.
Exception = {"Cannot insert duplicate key row in object 'dbo.TBL#MadrakeTahsili' with unique index 'IX#MadrakeTahsiliName'.\r\nThe statement has been terminated."}
definition is
City Table(Id int,FK_Country int,name nvarchar(50))
Country Table(Id int,name nvarchar(50))
Id in City and Country table in Identity(Auto Increment)
Note : EF try to Insert a Country and then add the city to it But I want to add the city to a country that exist.
I don’t know what
Country.CreateCountry(CountryId);does, but in any case you need to get the existing country from the database through the EF context.That is, so that Entity Framework knows you want to use an existing country you need to “get” it through your dbContext and then assign it to the city. That way the
Countryentity will be “attached” and EF won’t try to create a new one.The reverse should work too: Get the country from the DB and add the
Cityto theCountryinstead of theCountryto theCity.