Updating child objects in Entity Framework 6

前端 未结 1 1575
抹茶落季
抹茶落季 2021-01-01 03:48

(Using Entity Framework 6.2)

I have the following two models/entities:

public class City
    {
        public int CityId { get; set; }
        public         


        
相关标签:
1条回答
  • 2021-01-01 04:33

    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.

    0 讨论(0)
提交回复
热议问题