Estou tentado fazer a seguinte consulta SQL com o Linq:
Essa é a estrutura do banco de dados:
Pessoas | type |
---|---|
Id | int |
Name | string |
Age | int |
Sons | int |
Pets | type |
---|---|
Id | int |
Name | string |
Adopted | bool |
PersonId | int (foreign key) |
Essa é a cosnulta crua que eu faço no SSMS
SELECT a.Id, count(b.Id) as pets, a.Name
FROM Pessoas AS a
LEFT JOIN Pets AS b
ON a.Id = b.PersonId
GROUP BY a.Id, a.Name
Essa é a versão com o Linq que eu fiz no visual studio:
var result = from p in _context.People
join pet in _context.Pets
on p.Id equals pet.Person.Id
group p by p.Id into wp
from subperson in wp.DefaultIfEmpty()
select new Person { Name = subperson.Name, PetsId = subperson.Pets.Count()};
E esse é o erro:
The LINQ expression 'DbSet<Person>()
.Join(
inner: DbSet<Pet>(),
outerKeySelector: p => p.Id,
innerKeySelector: pet => pet.Person.Id,
resultSelector: (p, pet) => new {
p = p,
pet = pet
})
.GroupBy(
keySelector: <>h__TransparentIdentifier0 => <>h__TransparentIdentifier0.p.Id,
elementSelector: <>h__TransparentIdentifier0 => <>h__TransparentIdentifier0.p)
.SelectMany(
collectionSelector: wp => wp
.AsQueryable()
.DefaultIfEmpty(),
resultSelector: (wp, subperson) => new Person{
Name = subperson.Name,
PetsId = subperson.Pets
.AsQueryable()
.Count()
}
)' could not be translated. Either rewrite the query in a form that can be translated
O que estou fazendo de errado? (Sou iniciante)