I have a c# object with date field and foreign key. I have created one double index on these fields.

public class Session : DbObject
    [Column(TypeName = "date")]
    [Index(IsUnique = false, Order = 2)]
    public DateTime Date { get; set; }

    [Index(IsUnique = false, Order = 1)]
    public int PatientId { get; set; }

    public Patient Patient { get; set; }     

I need to take a list from the 'Sessions' as follow: I have a list of patients ids and a date. I need to get one Session for each patient that its date is newest from all the rest.

something like this:

SELECT * FROM Sessions WHERE PatientId IN (1, 2, ...) AND TOP(Date < SOME_DATE)

I know this query is nonsense. It just to clarify my intention.

***It is important to use the indexes because this table is huge.

If it is possible, I would like to know if I can write it in c# and entity framework.

Thanks a lot!

1 Answers

David Browne - Microsoft On Best Solutions

***It is important to use the indexes because this table is huge.

The LINQ query would look something like:

var ids = new List<int>() { 1, 2, 3 };
var dt = DateTime.Now;
var q = from s in db.Sessions
        where ids.Contains(s.Id)
            && s.Date > dt
        group s by s.PatientId into byPatientId
        select byPatientId.OrderBy(s => s.Date).Take(1);

But that's perhaps not the most efficient query. If that's too slow, you might want to consider a store query instead:

with q as 
   select Date, 
          row_number() over (partition by PatientId order by Date desc) rn
   where PatientId in (1,2,3,5,6,3)
     and Date > @d
   from Sessions
select Date, PatientId
from q
where rn = 1
", dt);