【发布时间】:2020-02-27 10:17:05
【问题描述】:
在asp.net webapi 2中加入两个表需要帮助
我有以下代码加入两个表
public IQueryable<Employee> GetEmployees()
{
var q = (from n in db.Employees
join c in db.tblCities on n.ProjectID equals c.CityID
select new
{
n.Name,
n.Email,
c.CityName,
}).ToList();
return q;
}
但我得到这个错误
严重性代码描述项目文件行抑制状态 错误 CS0266 无法隐式转换类型 'System.Collections.Generic.List' 到 'System.Linq.IQueryable'。显式 存在转换(您是否缺少 投?)WebApplication15 C:\Users\admin\source\repos\WebApplication15\WebApplication15\Controllers\EmployeesController.cs 35 Active
员工模型
namespace WebApplication15
{
using System;
using System.Collections.Generic;
public partial class DtscEmployee
{
public int ID { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public string Country { get; set; }
public Nullable<int> ProjectID { get; set; }
public string ManagerName { get; set; }
public string ProfileImage { get; set; }
}
}
城市模型
namespace WebApplication15
{
using System;
using System.Collections.Generic;
public partial class tblCity
{
public int CityID { get; set; }
public string CityName { get; set; }
}
}
【问题讨论】:
-
你的函数的返回类型是什么
-
发布完整功能。最有可能的函数返回类型是 IQueryable
但你返回 q (它的类型是 Generic List) -
这是因为返回类型与
listtype 不同。函数返回类型是什么? -
@BPDESILVA 我尝试将其作为 `IQueryable
q = (from n in db.Employees` 并最后将 .ToList(); 替换为 ToList().AsQueryable(); return q ; -
删除 ToList() 对您没有帮助。您需要了解代码才能找到问题。您的 select new 创建了一个匿名对象,它不再是您的
employee,因此您无法返回它。现在,你为什么要加入 Employee 和城市表。请记住,您使用的是对象而不是 SQL 表。因此,如果您的模型的设计方式使其具有对其子级的导航属性,那么您只需要返回“员工”。如果你是 EF 新手,请多阅读
标签: c# asp.net asp.net-web-api