【问题标题】:Get full object from collection in API request fail从 API 请求中的集合中获取完整对象失败
【发布时间】:2021-07-29 05:49:45
【问题描述】:

我正在尝试通过 API 从Persons Collection 获取对象,但它只返回相关Car 对象的null

人物模型:

public class Person
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string City { get; set; }
    public int Salary { get; set; }
    public DateTime PersonPublicationDate { get; set; }
    public bool IsActive { get; set; }
    public virtual Car Car { get; set; }
}

车型:

public class Car
{
    public int Id { get; set; }
    public string CarName { get; set; }
    public DateTime CarPublicationDate { get; set; }
}

获取方法:

[HttpGet]
[Route("GetPersonData/{id}")]
public Person GetPerson([FromRoute] int id)
{
    Person personData = _context.Persons.FirstOrDefault(a => a.Id == id);
    return personData;
}

personData 中,当要求Car 时,它只返回null。我在这个地方只需要一个人的数据,他的Car 是这样的:

{
    "id": 4,
    "name": "Jan Bojanowski",
    "city": "Warszawa",
    "salary": 1245,
    "personPublicationDate": "2018-02-02T00:00:00",
    "isActive": true,
    "car": {
        "id": 2,
        "carName": "Skoda",
        "carPublicationDate": "2018-10-01T00:00:00"
    }
}

【问题讨论】:

    标签: angular asp.net-core asp.net-core-webapi


    【解决方案1】:

    通过执行简单查询,您将获得的唯一数据是对象本身:

    Person personData = _context.Persons.FirstOrDefault(a => a.Id == id);
    

    要正确获取数据,您必须要求同时包含相关对象:

    Person personData = _context.Persons
                                .Include(person => person.Car)
                                .FirstOrDefault(a => a.Id == id);
    

    本主题推荐阅读:https://docs.microsoft.com/en-gb/ef/core/querying/related-data

    【讨论】:

      猜你喜欢
      • 2021-03-29
      • 2018-12-04
      • 1970-01-01
      • 2019-07-09
      • 2015-04-03
      • 2018-05-21
      • 2022-11-06
      • 1970-01-01
      • 2019-03-06
      相关资源
      最近更新 更多