How to add/update/delete n-n tables?
How to add/update/delete n-n tables?
I've this tables on my SQL Server Database:

On my ASP.NET MVC app I manage the Clinics for each Medical. So let say Medical ID 1 can have N associated Clinics, such as Clinic ID 5, 8, 10.
ASP.NET MVC
Clinics
Medical
Medical ID 1
Clinic ID 5, 8, 10
Here's my attempt in the Controller's Action:
Controller's Action
if (ModelState.IsValid)
Medicals medical = mapper.Map<MedicalViewModel, Medicals>(medicalViewModel);
// medical
ctx.Entry(medical).State = medical.ID == 0 ? EntityState.Added : EntityState.Modified;
ctx.SaveChanges();
// relationships medical/clinics
foreach (var clinic in medicalViewModel.ClinicsList)
Clinics clinics = new Clinics() ID = clinic.ID ;
// delete
if (!clinic.IsChecked)
medical.Clinics.Remove(clinics);
// add/update
else
medical.Clinics.Add(clinics);
ctx.SaveChanges();
But its not able to either delete or add/update.
Where am I wrong? I don't have the table ClinicsMedicals generated by Entity Framework, so I guess I need to access by Medicals.
ClinicsMedicals
Entity Framework
Medicals
Its what I'm trying to do, but using code and entity relationship directly :)
– markzzz
Aug 22 at 13:31
haven't used EF in a long time, doesnt it create a ClinicsMedical class for you? maybe you can remove that class first before you remove the relationship.
– mahlatse
Aug 22 at 13:33
He no, there isn't :) I don't need to remove Medicals or Clinics, but its relationship (such as the clinics associated at the Medical, or add new ones).
– markzzz
Aug 22 at 13:48
1 Answer
1
Here is what I think you need to do:
if (ModelState.IsValid)
Medicals medicalEntity;
if(medicalViewModel.ID == 0)
medicalEntity = ctx.Set<Medicals>().Add(new Medicals());
else
// retrieve existing entity
medicalEntity = ctx.Set<Medicals>().Find(medicalViewModel.ID);
if(medicalEntity == null)
// log and throw exception may be?
// apply new changes to existing entity
medicalEntity = mapper.Map<MedicalViewModel, Medicals>(medicalViewModel, medicalEntity);
// relationships medical/clinics
foreach (var clinicViewModel in medicalViewModel.ClinicsList)
var clinicEntity = medicalEntity.Clinics.FirstOrDefault(x => x.ID == clinicViewModel.ID);
// delete
if (!clinicViewModel.IsChecked)
medicalEntity.Clinics.Remove(clinicEntity);
else
if(clinicEntity == null) // add
medicalEntity.Clinics.Add(ctx.Set<Clinics>().Find(clinicViewModel.ID));
else
// update
ctx.SaveChanges();
It seems to works perfectly! Note: typo
FirstOfDefault, its "or" default ;)– markzzz
Aug 23 at 7:21
FirstOfDefault
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
In nornam sql , you would have to delete the link between then before you can link them, that means deleting ClinicsMedicals before you can delete either clinic or medicals
– mahlatse
Aug 22 at 13:25