0

I'm trying to write this query in linq

SELECT        dbo.Tbl_Users.ID, COUNT(dbo.Tbl_Inputs.ID) AS Inputs
FROM            dbo.Tbl_Users LEFT JOIN
                          dbo.Tbl_Inputs ON dbo.Tbl_Inputs.User_ID = dbo.Tbl_Users.ID
GROUP BY dbo.Tbl_Users.ID

this is my linq code, I made a class User() which holds the userid and the count of inputs the user made in Tbl_Inputs:

List<User> GetAllUsers()
        {
            List<User> userlist = new List<User>();
            userlist = (from u in Data.Tbl_Users
                        join i in Data.Tbl_Inputs on u.ID equals i.User_ID
                        into Joined
                        from p in Joined.DefaultIfEmpty()
                       group p by new { u.ID }
                       into grp select new User()
                       {
                            Id = grp.Key.ID,
                            Inputs = grp.Count()
                       }).ToList();

            return userlist;
        }

The problem is if the input is 0 it returns 1.

Can't figure it out.

Thanks

brent
  • 363
  • 2
  • 4
  • 12

2 Answers2

3

I think you need to check for null child when getting count. Try replacing your line with below:

Inputs = grp.Count(t=>t.User_ID != null)
Shital Shah
  • 63,284
  • 17
  • 238
  • 185
1

I know it's been a long time, but for registration, you can do the following to bring the value 0:

inputs = grp.Count(t => t > 0);
  • Value 1 is brought because the count function counts null values. So, if your result is null, the value will be 1. You can see more here: https://stackoverflow.com/a/44636034/2607793 – Daniel Jorge de Souza Nov 29 '17 at 13:12