Adnan Okko

Adnan Okko

  • NA
  • 19
  • 3.3k

Update tables with relations from ViewModel (EF)

Mar 22 2018 7:37 AM
I have the following entities:
  1. BIEntities db = new BIEntities();   
  2. public class SALES  
  3. {  
  4.    public int IDs {getset;}  
  5.    public string product { getset; }  
  6.    ICollection<COUNTRIES> COUNTRIES { getset; }  
  7.    ICollection<PRICES> PRICES { getset; }  
  8. }  
  9.    
  10. public class COUNTRIES  
  11. {  
  12.    public int IDc { getset; }  
  13.    public string country { getset; }  
  14.    public virtual SALES SALES { getset; }  
  15. }  
  16.    
  17. public class PRICES  
  18. {  
  19.    public int IDp { getset; }  
  20.    public string price { getset; }  
  21.    public string strength { getset; }   
  22.    public virtual SALES SALES { getset; }  
  23. }  
And a ViewModel:
  1. public class myViewModel  
  2. {  
  3.    public int ID { getset; }  
  4.    public string product { getset; }  
  5.    List<string> country { getset; }  
  6.    List<string> price { getset; }  
  7.    List<string> strength { getset; }  
  8. }  
I am trying to update (edit) all entities from myViewModel:
  1. [HttpPost]  
  2. [ValidateAntiForgeryToken]  
  3. public ActionResult Edit(int id, FormCollection collection, myViewModel myModel)  
  4. {  
  5.     SALES sUpdate = db.SALES.FirstOrDefault(s => s.IDs == myModel.ID);  
  6.    if (sUpdate != null)  
  7.    {  
  8.       db.Entry(sUpdate).CurrentValues.SetValues(myModel);  
  9.       db.SaveChanges();  
  10.    }  
  11.    return RedirectToAction("Index");  
  12. }  
I am getting this exception:
 
"System.InvalidOperationException: The view 'Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.' or its master was not found or no view engine supports the searched locations."
 
Is this method correct? what other methods can I use to update the tables?

Answers (6)