0

tenho os models departamento e instituição, como se vê a seguir.

public class Institution
{
   public long? InstitutionId { get; set; }
   public string Name { get; set; }
   public string Address { get; set; }
   public virtual ICollection<Department> Departments { get; set; }
}

public class Department
{
   public long? DepartmentId { get; set; }
   public string Name { get; set; }
   public long? InstitutionId { get; set; }
   public Institution Institution { get; set; }
}

Estou tentando mostrar numa view os departamentos agrupados por instituição. Eis o meu controller e o meu service:

//controller
public async Task<IActionResult> DepartmentGroupedByInstitution()
{
   return View(await _departmentService.GetDepartmentGroupedByInstitution());
}

//service
public async Task<List<IGrouping<Institution, Department>>> GetDepartmentGroupedByInstitution()
{
   var result = await _context.Departments.Include(d => d.Institution).OrderBy(d => d.InstitutionId).GroupBy(d => d.Institution).ToListAsync();            
   return result;
}

Porém, o seguinte erro acontece:

InvalidOperationException: The LINQ expression 'DbSet<Department>()
.OrderBy(d => d.InstitutionId)
.Join(
inner: DbSet<Institution>(),
outerKeySelector: d => EF.Property<Nullable<long>>(d, "InstitutionId"),
innerKeySelector: i => EF.Property<Nullable<long>>(i, "InstitutionId"),
resultSelector: (o, i) => new TransparentIdentifier<Department, Institution>(
Outer = o,
Inner = i
))
.GroupBy(
keySelector: d => d.Inner,
elementSelector: d => d.Outer)' could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to 'AsEnumerable', 'AsAsyncEnumerable', 'ToList', or 'ToListAsync'. See https://go.microsoft.com/fwlink/?linkid=2101038 for more information.

Alguém, por gentileza, poderia ajudar? Desde já agradeço.

2
  • Você leu a mensagem do erro? 13/01/2021 às 18:39
  • Boa noite, Leandro. Li sim e até pesquisei algo a respeito. Mas comecei a estudar asp net tem pouco tempo, então ainda estou dando os primeiros passos. Realmente não consegui compreender qual foi o problema. 18/01/2021 às 22:22

1 Resposta 1

0

Este erro acontece provavelmente por causa da sequência da chamada dos elementos na query.

Tenta trocar isso:

var result = await _context.Departments.Include(d => d.Institution).OrderBy(d => d.InstitutionId).**GroupBy**(d => d.Institution).ToListAsync();

Por isso:

var result = await _context.Departments.Include(d => d.Institution).GroupBy(d => d.Institution).OrderBy(d => d.InstitutionId).ToListAsync();            

Você deve fazer log-in para responder a esta pergunta.

Esta não é a resposta que você está procurando? Pesquise outras perguntas com a tag .