LINQ-to-SQL - Join, Count

Posted by ile on Stack Overflow See other posts from Stack Overflow or by ile
Published on 2010-05-28T07:03:59Z Indexed on 2010/05/28 7:31 UTC
Read the original article Hit count: 222

Filed under:
|
|

I have following query:

var result = (
             from role in db.Roles
             join user in db.Users on role.RoleID equals user.RoleID                         
             where
                 user.CreatedByUserID == userID                             
             orderby user.FirstName ascending
             select new UserViewModel
             {
                 UserID = user.UserID,
                 PhotoID = user.PhotoID.ToString(),
                 FirstName = user.FirstName,
                 LastName = user.LastName,
                 FullName = user.FirstName + " " + user.LastName,
                 Email = user.Email,
                 PhoneNumber = user.Phone,
                 AccessLevel = role.Name
             });

Now, I need to modify this query... Other table I have is table Deals. I would like to count how many deals user created last month and last year. I tried something like this:

var result = (
             from role in db.Roles
             join user in db.Users on role.RoleID equals user.RoleID
             //join dealsYear in db.Deals on date.Year equals dealsYear.DateCreated.Year
             join dealsYear in
                 (
                         from deal in db.Deals
                         group deal by deal.DateCreated into d
                         select new { DateCreated = d.Key, dealsCount = d.Count() }
                 ) on date.Year equals dealsYear.DateCreated.Year into dYear
             join dealsMonth in
                 (
                         from deal in db.Deals
                         group deal by deal.DateCreated into d
                         select new { DateCreated = d.Key, dealsCount = d.Count() }
                 ) on date.Month equals dealsMonth.DateCreated.Month into dMonth
             where
                 user.CreatedByUserID == userID                 
             orderby user.FirstName ascending
             select new UserViewModel
             {
                 UserID = user.UserID,
                 PhotoID = user.PhotoID.ToString(),
                 FirstName = user.FirstName,
                 LastName = user.LastName,
                 FullName = user.FirstName + " " + user.LastName,
                 Email = user.Email,
                 PhoneNumber = user.Phone,
                 AccessLevel = role.Name,
                 DealsThisYear = dYear,
                 DealsThisMonth = dMonth
             });

but here is even syntax not correct. Any idea?

Btw, is there any good book of LINQ to SQL with examples?

© Stack Overflow or respective owner

Related posts about linq-to-sql

Related posts about join