Create a view object of two different tables using entity

0

I need to return a DataView in Edit view but the view is filled with two different tables.

What I need is to know how to return an object PatientView of my two tables, patient and people

This is the Edit controller:

public async Task<ActionResult> Edit(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }

            var patient = await _db.Patients.FindAsync(id);

            if (patient == null)
            {
                return HttpNotFound();
            }

            var person = await _db.People.FindAsync(patient.PersonId);

            if (person == null)
            {
                return HttpNotFound();
            }     

         //in that place is that i need to send a PatientView
        return View(person);
    }

This is the PatientView:

[NotMapped]
    public class PatientView: Person 
    {
        public int Record { get; set; }
        public int PatientId { get; set; }
        [Display(Name = "Fecha de Ingreso")]
        [DataType(DataType.Date)]
        [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
        public DateTime? CreationDate { get; set; }

        [Display(Name = "Seguro Principal")]
        public int InsuranceId { get; set; }
        [Display(Name = "Tipificacion Sanguinea")]
        public int BloodTypeId { get; set; }

        [Display(Name = "Edad")]
        [MaxLength(10, ErrorMessage = "La longitud maxima del campo es {1} caracteres")]
        public string Age { get; set; }

        [Display(Name = "Imagen")]
        public HttpPostedFileBase ImageFile { get; set; }  

    }

This is the table of people:

public class Person
    {
        [Key]
        public int PersonId { get; set; }

        //[Required(ErrorMessage = "El Campo es requerido")]
        [MaxLength(15, ErrorMessage = "La longitud maxima del campo es {1} caracteres")]
        [Display(Name = "RNC/Cedula")]
        public string Rnc { get; set; }

        [Required(ErrorMessage = "El Campo es requerido")]
        [MaxLength(50, ErrorMessage = "La longitud maxima del campo es {1} caracteres")]
        [Display(Name = "Nombre")]
        public string Name { get; set; }

        [Required(ErrorMessage = "El Campo es requerido")]
        [MaxLength(50, ErrorMessage = "La longitud maxima del campo es {1} caracteres")]
        [Display(Name = "Apellido")]
        public string LastName { get; set; }

        [Display(Name = "Fecha de Nacimiento")]
        [DataType(DataType.Date)]
        [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
        public DateTime? BornDate { get; set; }

        [Display(Name = "Genero")]
        public int GenderId { get; set; }
        [Display(Name = "Nivel Escolar")]
        public int? SchoolLevelId { get; set; }

        [Display(Name = "Nacionalidad")]
        public int CountryId { get; set; }

        [MaxLength(50, ErrorMessage = "La longitud maxima del campo es {1} caracteres")]
        [DataType(DataType.EmailAddress)]
       // [Index("Person_Email_Index", IsUnique = true)]
        [Display(Name = "Correo")]
        public string Email { get; set; }

        [MaxLength(50, ErrorMessage = "La longitud maxima del campo es {1} caracteres")]
        [DataType(DataType.PhoneNumber)]
       // [Index("Person_Tel_Index", IsUnique = true)]
        [Display(Name = "Telefono")]
        public string Tel { get; set; }

        [MaxLength(50, ErrorMessage = "La longitud maxima del campo es {1} caracteres")]
        [DataType(DataType.PhoneNumber)]
    //    [Index("Person_Cel_Index", IsUnique = true)]
        [Display(Name = "Celular")]
        public string Cel { get; set; }

        [Display(Name = "Estatus Marital")]
        public int MaritalSituationId { get; set; }

        [Display(Name = "Ocupacion")]
        public int OcupationId { get; set; }

        [Display(Name = "Religion")]
        public int ReligionId { get; set; }

       // [Required(ErrorMessage = "El Campo es requerido")]
        [MaxLength(200, ErrorMessage = "La longitud maxima del campo es {1} caracteres")]
        [DataType(DataType.MultilineText)]
        [Display(Name = "Direccion")]
        public string Address { get; set; }

        [Display(Name = "Estatus")]
        public int StatusId { get; set; }

        [DataType(DataType.ImageUrl)]
        [Display(Name = "Imagen")]
        public string Imagen { get; set; }

        [Display(Name = "Autor")]
        public int AuthorId { get; set; }

        public virtual Gender Gender { get; set; }
        public virtual MaritalSituation MaritalSituation { get; set; }
        public virtual Ocupation Ocupation { get; set; }
        public virtual Religion Religion { get; set; }
        public virtual Country Country { get; set; }
        public virtual Status Status { get; set; }
        public virtual Author Author { get; set; }
        public virtual SchoolLevel SchoolLevel { get; set; }
        public virtual ICollection<Patient> Patients { get; set; }


    }

This is my patient table:

  public class Patient
    {
        [Key]
        public int PatientId { get; set; }
        public int PersonId { get; set; }
        public int Record { get; set; }
        [Display(Name = "Fecha de Ingreso")]
        [DataType(DataType.Date)]
        [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
        public DateTime? CreationDate { get; set; }
        [Display(Name = "Seguro Principal")]
        public int InsuranceId { get; set; }
        [Display(Name = "Tipificacion Sanguinea")]
        public int BloodTypeId { get; set; }
        [Display(Name = "Edad")]
        [MaxLength(10, ErrorMessage = "La longitud maxima del campo es {1} caracteres")]
        public string Age { get; set; }
        public virtual Person Person { get; set; }
        public virtual BloodType BloodType { get; set; }
        public virtual Insurance Insurance { get; set; }
       } 

This is the Create Post that I'm using, if you thing that theres something to improve

Translation: This is the view for Create. In case you think there is something to improve:

      public async Task<ActionResult> Create(PatientView view)
           {
                    var people = ToPeople(view);     
                    people.StatusId = 1;
                    _db.People.Add(people);
                    _db.SaveChanges();
                    var patient = ToPatient(view);
                    patient.PersonId = people.PersonId;                            
                    _db.Patients.Add(patient);    
                    await _db.SaveChangesAsync();
           }
    
asked by sGermosen 02.07.2017 в 04:00
source

2 answers

1

I solved it in a similar way to what Einer proposes, create a method that receives two variables of the types of my tables and build the structure

 private static PatientView ToView(Person pview, Patient view)
        {
            if (pview == null) throw new ArgumentNullException(nameof(pview));
            return new PatientView()
            {
                PersonId = pview.PersonId,
                AuthorId = pview.AuthorId,
                Imagen = pview.Imagen,
                StatusId = pview.StatusId,
                Address = pview.Address,
                ReligionId = pview.ReligionId,
                OcupationId = pview.OcupationId,
                MaritalSituationId = pview.MaritalSituationId,
                Cel = pview.Cel,
                Tel = pview.Tel,
                Email = pview.Email,
                CountryId = pview.CountryId,
                GenderId = pview.GenderId,
                BornDate = pview.BornDate,
                LastName = pview.LastName,
                Name = pview.Name,
                Rnc = pview.Rnc,
                PatientId = view.PatientId,
                Record = view.Record,
                CreationDate = view.CreationDate,
                InsuranceId = view.InsuranceId,
                BloodTypeId = view.BloodTypeId,
                SchoolLevelId = pview.SchoolLevelId,
                Age=view.Age,
                FullName=pview.Name + " " + pview.LastName

            };
        }
    
answered by 04.07.2017 / 15:07
source
1

You can do it with a join:

var personViewModel = (from person in _db.People
                       join patient in _db.Patients
                       on person.Id equals patient.PersonId

                      where person.Id = idPersona
                      select new PatientView{
                             Id = person.Id,
                             BloodTypeId = patient.BloodTypeId
                             //llena las demas propiedades del viewmodel con person y patient
                     }).ToList();

Or doing 2 queries:

var person = _db.People.Find(personId);
var patient = _db.Patients.FirstOrDefault(x=>x.PersonId == personId);

var patienteViewModel = new PatientView{
 Id = person.Id,
 BloodTypeId = patient.BloodTypeId
 //llena las demas propiedades del viewmodel con person y patient
};
    
answered by 03.07.2017 в 15:25