【发布时间】:2019-07-20 16:25:23
【问题描述】:
我正在使用 Webapi,并且我在数据库中有两个表以及 Department 和 Info 表。部门表与信息表有关系。我正在使用实体框架从数据库中检索数据,但我只从一个表 INFO 中获取数据,因此部门表显示 NULL 它必须显示部门数据,因为两者都有关系。
没有 Webapi,代码可以正常工作。那么我错在哪里,为什么部门表没有在 webapi 中显示。
希望你能理解我的问题,谢谢。
控制器
public class WebApiController : ApiController
{
[HttpGet]
public IHttpActionResult EmployeeList()
{
var List = DB.Infoes.ToList().OrderByDescending(x => x.ID);
return Json(List);
}
}
型号
public partial class Info
{
public int ID { get; set; }
public string Image_Name { get; set; }
public string First_Name { get; set; }
public string Last_name { get; set; }
public string Desription { get; set; }
public Nullable<int> DeprtmentIDFK { get; set; }
public virtual Department Department { get; set; }
}
public partial class Department
{
public int DepartmentID { get; set; }
public string DepartmentName { get; set; }
public virtual ICollection<Info> Infoes { get; set; }
}
【问题讨论】:
-
你必须包含它:
DB.Infoes.Include(info => info.Department).ToList() -
显示此错误.....无法将 lambda 表达式转换为类型“字符串”,因为它不是委托类型
-
你需要引用这个命名空间:
using System.Data.Entity; -
作为旁注,由于显而易见的原因,List 不是变量名的好选择。像 list 或 infoes 这样的东西会更好。
标签: c# entity-framework asp.net-web-api