【问题标题】:Get data from relational tables using entity framework C# WebApi使用实体框架 C# WebApi 从关系表中获取数据
【发布时间】: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 =&gt; info.Department).ToList()
  • 显示此错误.....无法将 lambda 表达式转换为类型“字符串”,因为它不是委托类型
  • 你需要引用这个命名空间:using System.Data.Entity;
  • 作为旁注,由于显而易见的原因,List 不是变量名的好选择。像 list 或 infoes 这样的东西会更好。

标签: c# entity-framework asp.net-web-api


【解决方案1】:

正如here 所讨论的那样,为了获取导航属性,您必须在您的 IQueryable 中 Include 它们,否则您总是会得到空值。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-01-02
    • 2017-05-23
    • 1970-01-01
    • 2015-07-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多