Mouhssine tahri

Mouhssine tahri

  • NA
  • 201
  • 11k

MVC 5, Entity Framework 6 and Many to Many Relationship

Oct 13 2020 10:53 AM
I've two model classes:
  1. public Service()  
  2.      public int CodeService { getset; }  
  3.      public string DesignationService { getset; }  
  4.      public virtual ICollection<User> ServiceToUser { getset; }  
  5. public User()  
  6.     public int UserID { getset; }  
  7.     public string FirstName { getset; }  
  8.     public virtual ICollection<Service> UserToService { getset; }  
  9. }  
The above code generates me 3 tables Service, User & ServiceUsers(autogenerated by EF)
 
i want insert in UserID = 5 and CodeService = 8 in ServiceUsers table.()
 
values 5 already exist in table User
values 8 already exist in table Service
 
i use webapi
  1. var apiurl = "http://localhost:14405/api/ServiceApi";  
  2. var data = {           
  3.     DesignationService: $("#description").val(),  
  4.     serviceToUser: user // usr is list of user with  userid=5  
  5. }  
  6.               
  7. $.ajax({  
  8.     url: apiurl,  
  9.     type: 'POST',  
  10.     dataType: 'json',  
  11.     data: data,  
  12.     success: function (d) {  
  13.     noty({ text: 'Association réussie', layout: 'topRight', type: 'success'   
  14.     });  
  15. },  
  16. error: function () {  
  17.       noty({ text: 'Association échouée', layout: 'topRight', type: 'error' });  
  18.       }  
  19. });   
  20.    
  21. public void addService(Service service)  
  22. {  
  23.     Attach(service);  
  24.     bd.Service.Add(service);  
  25.     bd.SaveChanges();  
  26. }   
  27. private void Attach(Service service)  
  28. {  
  29.     int l = service.ServiceToUser.Count();  
  30.     for (int i = 0; i < l; i++)  
  31.     {  
  32.         bd.User.Attach(service.ServiceToUser.ElementAt<User>(i));  
  33.      }  
  34. }  
but when addService is executed it create a new record in service table value 6 and in ServiceUsers table it create 6 for code service and 5 in userid.
 
can you help me to solve this problem.
 
I want only insert ServiceUsers
 
thanks

Answers (6)