无法将var类型转换为列表对象[重复]

问题描述 投票:-1回答:2

我将返回的项存储到var类型,然后尝试将其绑定到模型类类型的列表对象。但是这样做会给出错误说,

不能隐式地将类型System.collections.generic.list<AnonymousType>转换为System.Collections.Generic.List<MyService.Models.EmpModel>

请帮我解决这个问题。

public IEnumerable<EmpModel> GetEmpDetailsById(int id)
{
    var EmpList = (from a in EmpDet 
    where a.EmpId.Equals(id) 
    select new { a.EmpId, a.Name, a.City });

    List<EmpModel> objList = new List<EmpModel>();
    objList = EmpList.ToList(); // gives error here

    return objList;
}
c# .net linq
2个回答
1
投票

您可以在一个声明中执行此操作

return (from a in EmpDet 
    where a.EmpId.Equals(id) 
    select new EmpModel 
               { EmpId = a.EmpId, 
                 Name = a.Name, 
                 City = a.City 
               }).ToList();

}

1
投票

objList的类型是List<EmpModel>,但是你要返回Listanonymous type。您可以像这样更改它:

var EmpList = (from a in EmpDet 
    where a.EmpId.Equals(id) 
    select new EmpModel { EmpId = a.EmpId, Name = a.Name, City = a.City });

如果你仍然得到错误可能是因为你无法投影到映射的实体上,那么你需要从EmpModel实体创建一个具有所需属性的DTO类,如下所示:

public class TestDTO
{
    public string EmpId { get; set; }
    public string Name { get; set; }
}

然后你可以:

select new TestDTO { EmpId = a.EmpId, Name = a.Name }
© www.soinside.com 2019 - 2024. All rights reserved.