基于约定 Entity Framework 使用 Web 时核心返回与外键关联的对象 API
Convention based Entity Framework Core returning the object associated with the foreign key when using Web API
我首先使用 EF 代码。按照惯例,我添加了一个外键和一个对外部对象的引用(我相信这是需要的)。当我向 API 发送 Get
请求时,它 returns 一个 IEnumerable
。问题是每条记录还返回 returns 外键的完整对象。
我已经尝试在 SO 上使用谷歌搜索答案和问题。我尝试注释掉对其他对象的引用,但这没有用。
public class Bill
{
// other properties
public Guid PersonId { get; set; } // this is the foreign key
public Person Person { get; set; } // this is the reference to the foreign object
}
这是执行 Get 请求时返回的内容:
[
{
//other fields
"personId": "c28e52b0-1e40-46c4-812b-a61be7a69d53",
"person": {
//the entire other person object is returned here
}
},
]
如何在不为每个模型建立 DTO 的情况下解决这个问题?
我想知道我是否错误地使用了代码优先约定。
ASP.NET 核心 2.2 没有像 2.1 那样 return 类型 Json(Object)
。
ActionResult return匿名类型是一种选择,如果您不想使用 DTO。
public IActionResult Get()
{
return new OkObjectResult(new { PersonId = 99, OtherProperty = "more stuff" });
}
响应正文:
{
"personId": 99,
"otherProperty": "more stuff"
}
如果需要 return 各种状态代码,请使用 ObjectResult:
return new ObjectResult(new { PersonId = 99, OtherProperty = "more stuff"}) {StatusCode = 200};
我首先使用 EF 代码。按照惯例,我添加了一个外键和一个对外部对象的引用(我相信这是需要的)。当我向 API 发送 Get
请求时,它 returns 一个 IEnumerable
。问题是每条记录还返回 returns 外键的完整对象。
我已经尝试在 SO 上使用谷歌搜索答案和问题。我尝试注释掉对其他对象的引用,但这没有用。
public class Bill
{
// other properties
public Guid PersonId { get; set; } // this is the foreign key
public Person Person { get; set; } // this is the reference to the foreign object
}
这是执行 Get 请求时返回的内容:
[
{
//other fields
"personId": "c28e52b0-1e40-46c4-812b-a61be7a69d53",
"person": {
//the entire other person object is returned here
}
},
]
如何在不为每个模型建立 DTO 的情况下解决这个问题?
我想知道我是否错误地使用了代码优先约定。
ASP.NET 核心 2.2 没有像 2.1 那样 return 类型 Json(Object)
。
ActionResult return匿名类型是一种选择,如果您不想使用 DTO。
public IActionResult Get()
{
return new OkObjectResult(new { PersonId = 99, OtherProperty = "more stuff" });
}
响应正文:
{
"personId": 99,
"otherProperty": "more stuff"
}
如果需要 return 各种状态代码,请使用 ObjectResult:
return new ObjectResult(new { PersonId = 99, OtherProperty = "more stuff"}) {StatusCode = 200};