Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

linq after groupby unable to get column values

I am getting data from multiple tables by joining and i want to group data on particular column value but after group by statement i can access my aliases and their properties. What mistake i am making?

public List<PatientHistory> GetPatientHistory(long prid)
{
    using(var db = new bc_limsEntities())
    {
        List<PatientHistory> result = 
            (from r in db.dc_tresult
             join t in db.dc_tp_test on r.testid equals t.TestId into x
             from t in x.DefaultIfEmpty()
             join a in db.dc_tp_attributes on r.attributeid equals a.AttributeId into y
             from a in y.DefaultIfEmpty()
             where r.prid == prid
             group new {r,t,a} by new {r.testid} into g
             select new PatientHistory
             {
                 resultid = r.resultid,
                 bookingid = r.bookingid,
                 testid = r.testid,
                 prid = r.prid,
                 attributeid = r.attributeid,
                 result = r.result,
                 Test_Name = t.Test_Name,
                 Attribute_Name = a.Attribute_Name,
                 enteredon = r.enteredon,
                 Attribute_Type = a.Attribute_Type
             }).ToList();
        return result;
    }
}
like image 508
Ehsan Sajjad Avatar asked Oct 04 '22 14:10

Ehsan Sajjad


1 Answers

You're doing this wrong way. As been said by Jon after grouping the sequences with aliases r,t,a doesn't exist. After grouping you receive the sequence g with sequances of r,t,a in each element of g. If you want get one object from each group (for example most recent) you should try this:

List<PatientHistory> result = 
    (from r in db.dc_tresult
     join t in db.dc_tp_test on r.testid equals t.TestId into x
     from t in x.DefaultIfEmpty()
     join a in db.dc_tp_attributes on r.attributeid equals a.AttributeId into y
     from a in y.DefaultIfEmpty()
     where r.prid == prid
     group new {r,t,a} by new {r.testid} into g
     select new PatientHistory
     {
         resultid = g.Select(x => x.r.resultid).Last(), // if you expect single value get it with Single()
         // .... here add the rest properties
         Attribute_Type = g.Select(x => x.a.Attribute_Type).Last()
     }).ToList();
like image 196
YD1m Avatar answered Oct 07 '22 19:10

YD1m