0

I'm trying to make some queries using EF-Core and I have the following code

public List<Visitation> GetAllVisitations()
    {
        return this.hospital.Visitations
            .Where(v => v.DoctorId == this.Doctor.Id)
            .Select(v => new Visitation
            {
                Doctor = v.Doctor,
                Patient = v.Patient,
                Date = v.Date,
                Comments = v.Comments
            })
            .ToList();
    }

public List<Visitation> GetVisitationByPatient(int id)
    {
        var patient = this.GetPatientById(id);

        return this.hospital.Visitations
            .Where(v => v.PatientId == patient.Id)
            .Select(v => new Visitation
            {
                Doctor = v.Doctor,
                Patient = v.Patient,
                Date = v.Date,
                Comments = v.Comments
            })
            .ToList();
    }

It is pretty obvious that the Select statement is the same in both methods. However I know that EF Core uses Expression<Func>, rather than Func therefore I do not know how to make an Expression, which can be used in both Select statements.

2
  • Have a look at the answer to this SO stackoverflow.com/questions/33607575/… Commented Jul 15, 2020 at 18:26
  • What type is hospital? Also, have you tried anything? Commented Jul 15, 2020 at 19:31

1 Answer 1

2

The query won't execute until you call .ToList(). So you may take the partial query up to the .Where() and pass it to a function that adds the Select() portion.

Something like this:

public List<Visitation> GetAllVisitations()
    {
        var query = this.hospital.Visitations
            .Where(v => v.DoctorId == this.Doctor.Id);
            
        return this.addTransformation(query)
                   .ToList();
    }

public List<Visitation> GetVisitationByPatient(int id)
    {
        var patient = this.GetPatientById(id);

        var query = this.hospital.Visitations
                        .Where(v => v.PatientId == patient.Id)
            
        return this.addTransformation(query)
                   .ToList();
    }

public IQueriable<Visitation> AddTransformation(IQueriable<Visitation> query)
{
     return query.Select(v => new Visitation
                {
                    Doctor = v.Doctor,
                    Patient = v.Patient,
                    Date = v.Date,
                    Comments = v.Comments
                });
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.