Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework Core using select and group by

I want to use select and groupby in my query

_context.UserChart_Tbl
        .Where(uc => uc.UserID == "6")
        .GroupBy(g => g.OrgnizationID)
        .Select(g => g.OrgnizationID)
        .ToArray();

But I get an error in select

Error CS1061 'IGrouping' does not contain a definition for 'OrgnizationID' and no accessible extension method 'OrgnizationID' accepting a first argument of type 'IGrouping' could be found (are you missing a using directive or an assembly reference?)

How can I solve this problem?

Update

Error Solved by this code

_context.UserChart_Tbl
          .Where(uc => uc.UserID == u.Id)
          .GroupBy(g => g.OrgnizationID)
          .Select(g => g.Key).ToArray()

Complete Code

    public List<DoctorDropDoenViewModel> DoctorDropDown()
    {
        var query = (from u in _context.Users
                     join
                     UR in _context.UserRoles on u.Id equals UR.UserId
                     join
                     D in _context.Doctor_Tbl on u.Id equals D.DoctorUserId
                     where UR.PolicyID == 4

                     select new DoctorDropDoenViewModel()
                     {
                         DoctorID = u.Id,
                         DoctorFullName = u.FirstName + " " + u.Family,
                         OrgID = _context.UserChart_Tbl.Where(uc => uc.UserID == u.Id)
                         .GroupBy(g => g.OrgnizationID).Select(g => g.Key).ToArray()
                     });


      return query.ToList();
    }

And

public class DoctorDropDoenViewModel
{
    public string DoctorID { get; set; }
    public string DoctorFullName { get; set; }
    public int[] OrgID { get; set; }
}

DoctorID can have several OrgID Which may also be duplicates. I want to display duplicates only once. For this purpose i use Distinct and Group By.

But Group By not working

enter image description here

like image 550
topcool Avatar asked Sep 05 '26 03:09

topcool


1 Answers

Wwhen you are grouping items property which you are using for group is going to 'Key' of the group. Replace Select(g => g.OrgnizationID) with Select(g => g.Key) it should help.

like image 174
Vyacheslav Benedichuk Avatar answered Sep 07 '26 18:09

Vyacheslav Benedichuk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!