Mai Mai - 1 month ago 15
C# Question

Cannot implicitly convert type 'System.Collections.Generic.List<AnonymousType#1>' to 'System.Linq.IQueryable<MH_CRUD_Model.Member>'

I'm trying to display all the data of Member by merging First name and Last name to Name.
The function is successful. But it starts to give me error when I try to write the select function like this:

[HttpGet]
[Route("api/Members")]
public IQueryable<Member> GetMembers()
{
var member = db.Members.Select(m=>
new{
Name = m.LastName +" "+ m.LastName,
m.Title,
m.ProjectId
});
return member.ToList();

}


any Help

Answer

You are creating an anonymous type in your select statement without specifying any type. At the same time, your function return type is IQueryable<Member> and at the end of your function you are returning list of anonymous object type. You need to match the function return type and return data. Here is my solution

First create a model class for return data like named MemberReturn you can use name as your choice

class MemberReturn
{
    public string Name { get; set; }
    public string Title { get; set; }
    public string ProjectId { get; set; }

}

Then select data in linq query as MemberReturn type and change your function's return type as List<MemberReturn>

[HttpGet]
[Route("api/Members")]
public List<MemberReturn> GetMembers()
{
    var member = db.Members.Select(m=>
            new MemberReturn {
                Name = m.FirstName + " " + m.LastName,
                Title = m.Title,
                ProjectId = m.ProjectId
            });
    return member.ToList();

}
Comments