一对多关系的导航在c#中不起作用

本文关键字:不起作用 导航 关系 一对多 | 更新日期: 2023-09-27 18:04:23

我的数据库中有两个实体:Patient和Doctor,它们包含一对多关系。类如下:

public partial class Doctor
{
    public Doctor()
    {
        this.Patients = new HashSet<Patient>();
    }
    public int DoctorID { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Email { get; set; }
    public string Country { get; set; }
    public System.DateTime Birthday { get; set; }
    public byte[] Photo { get; set; }
    public string Password { get; set; }
    public string PasswordSalt { get; set; }
    public int SpecialityID { get; set; }
    public virtual Speciality Speciality { get; set; }
    public virtual ICollection<Patient> Patients { get; set; }
}

public partial class Patient
{
    public int PatientID { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Email { get; set; }
    public string Gender { get; set; }
    public string MaritalStatus { get; set; }
    public System.DateTime Birthday { get; set; }
    public string Phone { get; set; }
    public int DoctorID { get; set; }
    public System.DateTime EntryDate { get; set; }
    public virtual Doctor Doctor { get; set; }
    public virtual PatientAddress PatientAddress { get; set; }
}

这是为医生添加病人的代码。

public ActionResult AddPatient(PatientViewModel patientVM)
    {
        using (PeopleCareEntities PeopleEntities=new PeopleCareEntities())
        {
            PatientAddress patientAddress = Mapper.Map<PatientViewModel, PatientAddress>(patientVM);
            Patient patient = Mapper.Map<PatientViewModel, Patient>(patientVM);
            int currentDoctor = ((Doctor)Session["Doctor"]).DoctorID;
            //problem is here
            Doctor doctor=PeopleEntities.Doctors.Single(a=>a.DoctorID==currentDoctor);
            var doctorPatients = doctor.Patients.FirstOrDefault(a=>a.Email==patientVM.Email);
            if (doctorPatients==null)
            {
                patient.EntryDate = DateTime.Now;
                patient.DoctorID = doctor.DoctorID;
                doctor.Patients.Add(patient);
                PeopleEntities.SaveChanges();
                patientAddress.PatientID = patient.PatientID;
                PeopleEntities.PatientAddresses.Add(patientAddress);
                PeopleEntities.SaveChanges();
                return Json(new { Message = "Patient added successfully !" }, JsonRequestBehavior.AllowGet);
            }
            else
            {
                return Json(new { Message="Patient already exist !" }, JsonRequestBehavior.AllowGet);
            }
        }
    }

在数据库中添加患者工作正常,但doctor.Patients has always Count=0.处于调试模式。

一对多关系的导航在c#中不起作用

当加载doctor实体时,试试这个:

Doctor doctor=PeopleEntities.Doctors.Single(a => a.DoctorID == currentDoctor)
                                    .Include(a => a.Patients);