Dan Ekström
Dan Ekström

Reputation: 3

LINQ group by not working

I've read lots of group by replies in this forum, but I have to ask anyway:

var errandQuery = (from t in db.TimereportSet
                   group t by new { t.Errand.Name, t.Date } into g
                   select new ErrandTime { Date = g.Key.Date, Value = g.Sum(e => e.Hours) }).ToList();

why isn't this working. I get the following exception: "Unknown column 'GroupBy1.K1' in 'field list'"

the exception comes from the mySQLClient.

Upvotes: 0

Views: 3544

Answers (2)

user627930
user627930

Reputation: 3

I wrote this as a comment but it should be an answer, this is a confirmed bug in mySQL with LinQ. Is there another way of querying for the same thing using a work around, objectquery or direct sql or something else using the entity framework:

var errandQuery = (from t in db.TimereportSet
                   group t by new { t.Errand.Name, t.Date } into g
                   select new ErrandTime {
                       Date = g.Key.Date,
                       Value = g.Sum(e => e.Hours)}).ToList();

or should I create a new post for this question?

Upvotes: 0

TheGeekYouNeed
TheGeekYouNeed

Reputation: 7539

You're not selecting Hours into g, so they aren't there to sum.

I don't know what your data looks like but try this:

EDIT:

var errandQuery = (from t in db.TimereportSet                    
                   group t by new { t.Errand.Name, t.Date } into g                   
                   select new ErrandTime { Date = g.Key.Date, Value = g.Sum**(t => t.Hours)** }).ToList(); 

Sorry, my first response was incorrect.

You LINQ query is correct, except right at the end --- you are using e.. where you need to reference the items you selected ... so you would need to use t in your lambda expression instead of e

Upvotes: 1

Related Questions