Adnan Okko

Adnan Okko

  • NA
  • 19
  • 3.1k

Entity Framework one to many relation not updated

Mar 22 2018 12:06 PM
I have the following entities:
  1. BIEntities db = new BIEntities();  
  2.    
  3. public class SALES  
  4. {  
  5.    public int IDs {getset;}  
  6.    public string product { getset; }  
  7.    ICollection<COUNTRIES> COUNTRIES { getset; }  
  8. }  
  9. public class COUNTRIES  
  10. {  
  11.    public int IDc { getset; }  
  12.    public string country { getset; }  
  13.    public virtual SALES SALES { getset; }  
  14. }  
And a ViewModel:
  1. public class myViewModel  
  2. {  
  3.    public int ID { getset; }  
  4.    public string product { getset; }  
  5.    List<string> country { getset; }  
  6. }  
I am trying to update (edit) all entities from myViewModel:
  1. SALES sUpdate = db.SALES.FirstOrDefault(s => s.IDs == myModel.ID);  
  2. if (sUpdate != null)  
  3. {  
  4.    //This works fine!  
  5.    db.Entry(sUpdate).CurrentValues.SetValues(myModel);  
  6. }  
  7.    
  8. var cUpdate = from c in db.COUNTRIES where c.IDc == myModel.ID select c;  
  9. if (cUpdate != null)  
  10. {  
  11.    foreach (var item in cUpdate)  
  12.       {  
  13.          item.country = myModel.country;  
  14.          item.IDc = myModel.ID;  
  15.           
  16.          //What should I add here to update the records??  
  17.   
  18.       }  
  19. }  
  20. db.SaveChanges();   
This can update the main table "SALES" but table "COUNTRIES" is not updated.