(Using Entity Framework 6.2)
I have the following two models/entities:
public class City
{
public int CityId { get; set; }
public
You need to add Cities
to that particular Country
object which is being updated.
public Country Update(Country country)
{
using (var dbContext =new DbContext())
{
var countryToUpdate = dbContext.Countries.SingleOrDefault(c => c.Id == country.Id);
countryToUpdate.Cities.Clear();
foreach (var city in country.Cities)
{
var existingCity =
dbContext.Cities.SingleOrDefault(
t => t.Id.Equals(city.cityId)) ??
dbContext.Cities.Add(new City
{
Id = city.Id,
Name=city.Name
});
countryToUpdate.Cities.Add(existingCity);
}
dbContext.SaveChanges();
return countryToUpdate;
}
}
Update :
public class City
{
public int CityId { get; set; }
public string Name { get; set; }
[ForeignKey("Country")]
public int CountryId {get;set;}
public virtual Country Country {get; set;}
}
Hope it helps.