none
Insert Record in Many to Many relationship using generic repository RRS feed

  • Question

  • I have many to many relationship between doctor and clinic entities and also i am using unit of work generic Repository pattern. When i try to insert new doctor record i need to select multiple or single existing clinics. How can i insert doctor record with clinic reference and without duplication error.

    DoctorManager.cs
    ****************
        public void InsertDoctor(Doctor doctor)
        {           
          _unitOfWork.DoctorRepository.Insert(doctor); //doctor object has clinics selected
          _unitOfWork.Save();
         }

    GenericRepository.cs

        public virtual void Insert(TEntity entity)
        {
          _dbSet.Add(entity);
        }

    How can i  implement _dbSet.Attach(); in generic repository to ovoid duplication error.
    Could someone direct me with sample would be thankful.

        namespace DoctorBooking.DomainEntities
        {
           public class Doctor
           {
             [Key]
             public Int32 DoctorId { get; set; }
             public string LastName { get; set; }
             public string FirstName { get; set; }

             public virtual ICollection<Clinic> Clinics { get; set; }

            }
        }

        namespace DoctorBooking.DomainEntities
        {
           public class Clinic
           {
             [Key]
             public Int32 ClinicId { get; set; }
             public string Name { get; set; }
             public int ContactNumber { get; set; }
             public string Email { get; set; }        

             public virtual ICollection<Doctor> Doctors { get; set; }

           }
        }

    Thursday, May 23, 2013 2:33 AM

All replies

  • Hi Sanji,

    I think you can try the two solutions in this thread:

    http://stackoverflow.com/questions/8576916/ef-repository-pattern-many-to-many-insert

    You can either search the relational entity by primary key or create a new entity and attach it.

    Best regards,


    Chester Hong
    MSDN Community Support | Feedback to us
    Develop and promote your apps in Windows Store
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    Monday, May 27, 2013 5:06 AM
    Moderator
  • Thank you very much Chester. That is good point to start with. But my issue is when i have generic entity(Doctor) i am not able to reference the child collection(Clinics).

    public virtual void Insert(TEntity entity)
    {

       so should be find the object and add to the entity. Now i am able to get the collection of clinic   under doctor, But cant add them into Doctor.clinics.add();

    Like entity.????.add(xxx)

    How can i reference Clinics(????) in generic entity.

    }

    Thank you again

    Wednesday, May 29, 2013 12:42 AM