es.davy.ai

Preguntas y respuestas de programación confiables

¿Tienes una pregunta?

Si tienes alguna pregunta, puedes hacerla a continuación o ingresar lo que estás buscando.

Linq no devolverá una lista.

public IEnumerable GetEmployees()
{
var register2 = from a in context.Employees
join b in context.Accounts on a.NIK equals b.NIK
select new ProfileVM
{
NIK = a.NIK,
Password = b.Password,
};
return register2.ToList();
}

Tengo un Repositorio para llamar datos usando LINQ, quiero devolverlo para poder pasarlo a mi controlador, pero no puedo devolverlo.

csharp
return (IEnumerable)register2.ToList();

La IDE sugiere esto pero todavía no funciona, el error dice:

System.InvalidCastException: ‘No se puede convertir el objeto del tipo
‘System.Collections.Generic.List1[<>f__AnonymousType83[System.String,System.String,System.Int32]]’
al tipo ‘System.Collections.Generic.IEnumerable`1[API.ViewModel.ProfileVM]’.’

MiProfileVM

csharp
public class ProfileVM
{
public string NIK { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Gender { get; set; }
public string Phone { get; set; }
public string Password { get; set; }
public DateTime BirthDate { get; set; }
public int Salary { get; set; }
public string Email { get; set; }
public int GPA { get; set; }
public string Degree { get; set; }
public int UniversityId { get; set; }
}

Tags:  ,

Answer

  1. Avatar for davy.ai

    Necesitas mapear el tipo anónimo al tipo ProfileVM. Puedes utilizar el método Select para hacerlo.

    csharp
    public IEnumerable<profilevm> GetEmployees()
    {
    var register2 = from a in context.Employees
    join b in context.Accounts on a.NIK equals b.NIK
    select new ProfileVM
    {
    NIK = a.NIK,
    Password = b.Password,
    };
    return register2.ToList();
    }

Comments are closed.