我正在尝试通过API从Persons Collection
获取一个对象,但它只为相关的null
对象返回Car
。
人物模型:
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
中,当系统要求null
时,它仅返回Car
。我需要在这个地方只有一个人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"
}
}
答案 0 :(得分: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