【发布时间】:2019-11-13 03:00:37
【问题描述】:
如何从 Web API 控制器调用存储过程?
我有以下代码使用 Web API 从 SQL Server 数据库获取数据,我有 api 工作正常,但我想使用存储过程。
存储过程名称为uspStaffDirectoryGetAllXXXEmployeeInfo,我将其导入到.edmx 中为GetEmployeeInformation。
注意:存储过程包含来自另一个数据库的字段。
这是我的代码,它对我有用,但我想使用存储过程替换它。
private EmployeesEntities db = new EmployeesEntities();
public IHttpActionResult GetEmployees()
{
var query = (from emp in db.employees
select new
{
emp.employee_number,
emp.employee_photo,
emp.first_name,
emp.last_name,
});
var employees = query.ToList();
return Ok(employees);
}
这是我使用存储过程uspStaffDirectoryGetAllXXXXEmployeeInfo获取数据的代码:
private EmployeesEntities db = new EmployeesEntities();
//[HttpGet]
public List<uspStaffDirectoryGetAllXXXXEmployeeInfo_Result> Get()
{
List<uspStaffDirectoryGetAllXXXXEmployeeInfo_Result> emplist = new List<uspStaffDirectoryGetAllXXXXEmployeeInfo_Result>();
using (EmployeesEntities db = new EmployeesEntities())
{
var results = db.uspStaffDirectoryGetAllXXXXEmployeeInfo();
foreach (var result in results)
{
var employee = new uspStaffDirectoryGetAllXXXXEmployeeInfo_Result()
{
id = result.id,
Employee_Display_Name = result.Employee_Display_Name,
first_name = result.first_name,
last_name = result.last_name,
Employee_Phone = result.Employee_Phone,
Employee_Email = result.Employee_Email
};
emplist.Add(employee);
}
return emplist;
}
但是,当我运行 API 时,我不断收到此错误,我在任何地方都没有名为“Column1”的字段
System.Data.Entity.Core.EntityCommandExecutionException: '数据读取器与指定的 'EmployeesModel.uspStaffDirectoryGetAllXXXXEmployeeInfo_Result' 不兼容。类型的成员“Column1”在数据读取器中没有同名的对应列。'
在这条线上
public virtual ObjectResult<uspStaffDirectoryGetAllXXXEmployeeInfo_Result> uspStaffDirectoryGetAllXXXXEmployeeInfo()
{
return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction<uspStaffDirectoryGetAllXXXXEmployeeInfo_Result>("uspStaffDirectoryGetAllXXXXEmployeeInfo");
}
我错过了什么?我该如何解决?
【问题讨论】:
标签: asp.net asp.net-mvc asp.net-web-api stored-procedures