I am using entityFramework Core and got a LINQ query select, inner join, where and got the results. I need to add GroupBy and it an error. I followed a few posts and mimic their code but I have been stucked.
I am having issue with translating to LINQ
Here is my linq that is working without the GroupBy
var result = this.myDbContent.Table1
.Join(this.Table2,
table1 => table1.myId,
table2 => table2.myId,
(table1 ,table2) => {table1 ,table2}
)
.Join(this.Table3,
table1_table2 => table1_table2.table1.myId,
table3 => table3.myId,
(table1_table2 ,table3) => {tabtable1_table2 e1 ,table3}
)
.Where(
s => s.table1_table2.table1.myId == 1 &&
s.table1_table2.table2.isCompleted == true
)
.Select(s => new
{
MyID = s.table1_table2.table1.myId,
MyDate = s.table1_table2.Table2.CompletedDate
});
This query works and returns records
In the following I added the GroupBy according to another post
var result = this.myDbContent.Table1
.Join(this.Table2,
table1 => table1.myId,
table2 => table2.myId,
(table1 ,table2) => {table1 ,table2}
)
.Join(this.Table3,
table1_table2 => table1_table2.table1.myId,
table3 => table3.myId,
(table1_table2 ,table3) => {tabtable1_table2 e1 ,table3}
)
.Where(
s => s.table1_table2.table1.myId == 1 &&
s.table1_table2.table2.isCompleted == true
)
.GroupBy(s => new
{
MyID = s.table1_table2.table1.myId,
MyDate = s.table1_table2.Table2.CompletedDate
}
)
.Select(s => new
{
MyID = s.Key.myId,
MyDate = s.Key.CompletedDate,
Count = s.Count()
});
When I run this query with the GroupBy, I get an"SYstem.InvalidOperationException
I am trying to add the following SELECT GROUPBY to the working QUERY
Select Count(*) AS Counts, MyID, MYDATE
FROM ( the working query above )
GROUP BY MyID, MYDATE
Thanks
Yourgroup key only has MyID
and MyDate
fields - the references to the joined tables are gone, so reference those in your select:
.Select(s => new
{
MyID = s.Key.MyID,
MyDate = s.Key.MyDate,
Count = s.Count()
}
Convert it to a list or Enumerable before grouping
var result = this.myDbContent.Table1
.Join(this.Table2,
table1 => table1.myId,
table2 => table2.myId,
(table1 ,table2) => {table1 ,table2}
)
.Join(this.Table3,
table1_table2 => table1_table2.table1.myId,
table3 => table3.myId,
(table1_table2 ,table3) => {tabtable1_table2 e1 ,table3}
)
.Where(
s => s.table1_table2.table1.myId == 1 &&
s.table1_table2.table2.isCompleted == true
).AsEnumerable()
.GroupBy(s => new
{
MyID = s.table1_table2.table1.myId,
MyDate = s.table1_table2.Table2.CompletedDate
}
)
.Select(s => new
{
MyID = s.Key.table1_table2.table1.myId,
MyDate = s.Key.table1_table2.Table2.CompletedDate,
Count = s.Count()
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.