如何添加/更新/删除n-n个表?

时间:2018-08-22 12:47:18

标签: sql-server asp.net-mvc entity-framework

我在SQL Server数据库中有此表:

enter image description here

在我的Stripe::InvalidRequestError: Order item currency usd does not match order currency eur. 应用中,我为每个currency管理ASP.NET MVC。因此,假设Clinics可以拥有N个关联的诊所,例如Medical

这是我在Medical ID 1中的尝试:

Clinic ID 5, 8, 10

但是它不能删除或添加/更新。

我在哪里错了?我没有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(); } ,所以我想我需要通过ClinicsMedicals访问。

1 个答案:

答案 0 :(得分:1)

这是我认为您需要做的:

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();
}