I wrote a SQL query to get a overview of sales revenue per car manufacturer.
Simple enough:
select
sum(s.Price * s.NumberOfCars) as Revenue, m.Name
from
Sale as s
join
Car as c on c.Id = s.CarId
join
Manufacturer as m on m.Id = c.ManufacturerId
group by
m.Name
That returns the following output:
Does anybody have an idea how to accomplish that with Entity Framework?
I tried this Linq:
var salez = from s in _context.Sale
join c in _context.Car on s.CarId equals c.Id
join m in _context.Manufacturer on c.ManufacturerId equals m.Id
group m by m.Name into g
select new Manufacturer()
{
Name = g.Key,
Revenue = g.Sum(s => s.)
};
I somehow can’t build the sum, as the table "s" is not available in the group "g".
I have also found quite similar questions, but none covered this case.
Similar question:
Further, I have tried the follwing:
SaleGroupManu = gret
.GroupBy(s => s.Car)
.Select(sc => new Car()
{
Umsatz = sc.Sum(s => s.Umsatz),
Manufacturer = sc.Key.Manufacturer
}).GroupBy(sc => sc.Manufacturer)
.Select(scm => new Manufacturer()
{
Name = scm.Key.Name,
Umsatz = scm.Sum(s => s.Umsatz)
}).ToList();
But I don’t find it very elegant, as I have to group by Car first, whilst with SQL, I can group by Manufacturer directly. It works, but is there any better idea?
I have tried raw sql, but it gave me errors, such as "The required column ‘Id’ was not present in the results of a ‘FromSql’ operation"
2
Answers
I have eventually worked it out, with the "!."-Syntax I didn't know about.
You can pass your working sql query directly into EF via
DbSet.SqlQuery()
as documented here:https://learn.microsoft.com/en-us/dotnet/api/system.data.entity.dbset.sqlquery?view=entity-framework-6.2.0