在实体框架和 WebAPI 中列出



我正在尝试使用实体框架在 .net webapi 中返回具有三列的员工,但返回给出错误,说无法将 pf 匿名类型转换为 emp..我错过了什么

public List<EMPLOYEE_DTLS> GetLoginInfo(string UserId)
{
var result = (from emp in db.EMPLOYEE_DTLS
where emp.UserId == UserId
select new
{
emp.FullName,
emp.Role,
emp.Designation
}).ToList();
return result;
}

您应该使用 DTO 返回列表。

public class EmployeeDTO
{
public string FullName {get; set;}
public string Role {get; set;}
public string Designation {get; set;}
}

public List<EmployeeDTO> GetLoginInfo(string UserId)
{
var result = (from emp in db.EMPLOYEE_DTLS
where emp.UserId == UserId
select new EmployeeDTO
{
FullName = emp.FullName,
Role = emp.Role,
Designation = emp.Designation
}).ToList();
return result;
}

您的方法返回List<EMPLOYEE_DTLS>,但您正在尝试返回匿名类型的列表。

假设EMPLOYEE_DTLS类具有属性FullNameRole并且Designation更改您选择的类型:

public List<EMPLOYEE_DTLS> GetLoginInfo(string UserId)
{
var result = (from emp in db.EMPLOYEE_DTLS
where emp.UserId == UserId
select new EMPLOYEE_DTLS
{
FullName = emp.FullName,
Role = emp.Role,
Designation = emp.Designation
}).ToList();
return result;
}

最新更新