I\'m fighting with linq trying to learn the syntax and I can\'t figure out how to do the following simple query
SELECT DISTINCT
user.firstname,
user.last
The query you're after should be pretty close to this:
var query =
from cu in company_user
where cu.company_id == 1
join u in user on cu.user_id equals u.user_id
join i in invoice on u.user_id equals i.user_id
group i.amount by new
{
u.firstname,
u.lastname,
} into gs
select new
{
firstname = gs.Key.firstname,
lastname = gs.Key.lastname,
count = gs.Count(),
sum = gs.Sum(),
};
Enjoy!
hey this site may help you:
101 Linq Samples
has examples of most of the linq functions, if u don't figure out, I may write for you later if somebody doesn't.
I think you have a discrepancy in your join clause -- you're inner joining invoice to itself on user_id. I assume that you intended to join this to user?
In any case, here's my best shot:
from inv in invoices
group inv by new { inv.user_id } into userInv
join usr in users on userInv.Key.user_id equals usr.user_id
where usr.company_user.company_id = 1
select new
{
usr.firstname,
usr.lastname,
amount = inv.Count(),
sum = inv.Sum(amt => amt.amount)
}
As for LINQ suggestions, I'd definitely suggest you download and play around with LINQPad. I use it all the time to test LINQ statements without Visual Studio. It'll convert your LINQ statements to SQL as well, which is probably of particular interest to you.
Edit: Enigmativity's statement is a lot closer to what you requested than mine is. I hadn't stumbled onto the column grouping in the examples I worked with.
Since op mentioned learning syntax, here's a fluent version:
company_user
.Where(x => x.company_id == 1)
.Join(
user,
x => x.user_id,
x => x.user_id,
(o,i) => new {
FirstName = i.firstName,
LastName = i.lastName,
InvoiceCount = invoice.Count(y => y.user_id == o.user_id),
InvoiceSum = invoice.Where(y => y.user_id == o.user_id).Sum(y => y.amount)
}
).GroupBy(x => new { x.FirstName, x.LastName })
.Distinct()