Dapper constantly returns the default value instead of the ID. What could be the problem and how to fix it? (Dapper + PostgreSQL)
Can you explain to me what is the problem?
public async Task<Appointment?> GetByIdWithPatientAndDoctorAsync(Guid id)
{
await using var connection = new NpgsqlConnection(connectionString);
await connection.OpenAsync();
const string query = """
select a.*,
p.*,
d.*,
c.*,
s.name as specializationname
from
appointments a
inner join
patients p on a.patientid = p.id
inner join
doctors d on a.doctorid = d.id
inner join
clinics c on a.clinicid = c.id
inner join
specializations s on d.specializationid = s.id
where
a.id = @Id
""";
var appointments = await connection.QueryAsync<Appointment, Patient, Doctor, Clinic, Specialization, Appointment>(
query,
(appointment, patient, doctor, clinic, specialization) =>
{
appointment.Patient = patient;
doctor.Specialization = specialization;
appointment.Doctor = doctor;
appointment.Clinic = clinic;
return appointment;
},
new { Id = id },
splitOn: "id, id, id, specializationname");
return appointments.FirstOrDefault();
}
public class Appointment : Entity
{
public Appointment() {}
public Appointment(DateTime date, Guid patientId, Guid doctorId, Guid clinicId, AppointmentStatus appointmentStatus)
{
Date = date;
PatientId = patientId;
DoctorId = doctorId;
ClinicId = clinicId;
AppointmentStatus = appointmentStatus;
}
public DateTime Date { get; set; }
public Guid PatientId { get; set; }
public Patient Patient { get; set; }
public Guid DoctorId { get; set; }
public Doctor Doctor { get; set; }
public Guid ClinicId { get; set; }
public Clinic Clinic { get; set; }
public AppointmentStatus AppointmentStatus { get; set; }
}
public abstract class Entity
{
protected Entity() {}
protected Entity(Guid id)
{
Id = id;
}
public Guid Id { get; }
}
I've already tried playing with splitOn
and leading through as ID to another name and nothing helped.
As mentioned in the comment, in the Entity
class the Id
property doesn't contain a setter. Thus it is not assigned with value, as default it is Guid.Empty
.
Add setter should resolve the problem.
public abstract class Entity
{
protected Entity() {}
protected Entity(Guid id)
{
Id = id;
}
public Guid Id { get; set; }
}