这个问题在这里已有答案:
我将返回的项存储到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;
}
您可以在一个声明中执行此操作
return (from a in EmpDet
where a.EmpId.Equals(id)
select new EmpModel
{ EmpId = a.EmpId,
Name = a.Name,
City = a.City
}).ToList();
}
objList的类型是List<EmpModel>
,但是你要返回List
的anonymous 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 }