Reputation: 1984
I need to get all the appointments from my table for a particular patient, for this I tried like,
public List<Appoinment> GetAppoinments() //here Appointment is a class.
{
List<Appoinment> appointments = null;
foreach (DataObject.Appointment appointment in
dataEntities.Appointments.Where(a => a.PATIENTID == PatientId))
{
}
return appointments;
}
in my Appointment class and table, I've fields like PatientId, doctorid, appointment date, like this,
here, within the foreach loop I tried like,
appointments.add(appointment);
its thorwing error, it can't convert automatically from database table appointments to class appointments, right.
I dunno how to do this, can anyone help me out here, thanks in advance
Upvotes: 1
Views: 6628
Reputation: 126547
public List<Appointment> GetAppointments()
{
return dataEntities.Appointments
.Where(a => a.PATIENTID == PatientId)
.Select(a => new OtherNamespace.Appointment
{
Id = a.Id,
Name = a.Name,
// etc.
})
.ToList();
}
Upvotes: 3
Reputation: 701
I agree with the solution above....however, If you have to write this sort of mapping code often... i.e. code to copy properties of one object into another, then you could consider using Automapper
https://github.com/AutoMapper/AutoMapper
Upvotes: 1
Reputation: 1121
You sloud conver the Data.Appointment to Your.Appointment.
You could do somthing like this.
My.Appoint resultAppointment = new My.Appointment();
resultAppointment.Id = dataAppointment.Id
But the better approach is to apply a projection over the data apointments. The generated sql query will get only the necesary fields
public List<Appoinment> GetAppoinments() //here Appointment is a class.
{
return dataEntities.Appointments.Where(a => a.PATIENTID == PatientId))
.Select(a => new Appointment() { Prop1 = a.Prop1})
.ToList();
}
Upvotes: 1
Reputation: 3996
You could do something like :
dataEntities.Appointments.Where(a => a.PATIENTID == PatientId)
.Select (new Appoinment { ... set values from DB element });
Upvotes: 1