WebAPI 从其他模型返回 json
本文关键字:返回 json 模型 其他 WebAPI | 更新日期: 2023-09-27 18:33:59
我可能我的搜索措辞错误,但我还没有找到任何与从控制器返回"更多"json相关的内容,而不仅仅是我正在使用的控制器/模型。我读到的内容让我想相信我的数据库存在关系或映射问题,但同样,我不确定从哪里开始。
目前我的控制器只返回:
{
"Id": 43,
"CreatedDate": "2015-02-09T00:00:00",
"CreatedBy": "username",
"ClosedDate": "2015-02-09T00:00:00",
"ClosedBy": "username",
"Revision": "1"
}
我正在尝试返回如下所示的内容:
{
"JobDetails": {
"Tasks": [{
"Id": 1,
"TaskName": "string",
"TaskDescription": "string",
"TaskOrder": 1,
"TimeCompleted": "DateTime",
"CompletedBy": "string",
"Notes": [{
"Note": "This is note 1.",
"CreatedDate": "DateTime",
"CreatedBy": "string"
}, {
"Note": "This is note 2.",
"CreatedDate": "DateTime",
"CreatedBy": "string"
}]
}]
}
}
内容来自我的"JobsController",在POST之后,您可以看到填充其他字段。
// POST: api/Jobs
[Route("api/Jobs/PostJob/", Name="PostJobRoute")]
[ResponseType(typeof(Job))]
public IHttpActionResult PostJob(Job job)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
//Run query to get a list of all tasks that have the group ID passed
IQueryable<Task> TasksQuery =
from c in db.Tasks
select c;
//Execute and loop results...
IQueryable<Task> TasksByGroupId = TasksQuery.Where(c => c.TaskGroupId == 1);
foreach (var task in TasksByGroupId)
{
db.JobDetails.Add(new JobDetail()
{
//Generate a new job detail for this job
JobId = job.Id,
TimeCompleted = DateTime.Now,
CompletedBy = "ocodyc",
TaskId = task.Id,
TaskIdOrder = task.TaskOrder
});
}
//TODO: Return a list of the task + notes
db.Jobs.Add(job);
db.SaveChanges();
return CreatedAtRoute("PostJobRoute", new { id = job.Id }, job);
}
这似乎是一个映射问题吗?我尝试将导航属性添加到"作业"到"作业详细信息",但这不起作用。
你返回你传递给操作的对象,这就是原因。 不要返回job
,执行以下操作:
var jobDetailList = new List<JobDetail>();
foreach (var task in TasksByGroupId)
{
jobDetailList.Add(new JobDetail()
{
//Generate a new job detail for this job
JobId = job.Id,
TimeCompleted = DateTime.Now,
CompletedBy = "ocodyc",
TaskId = task.Id,
TaskIdOrder = task.TaskOrder
});
}
//TODO: Return a list of the task + notes
db.Jobs.AddRange(jobDetailList);
db.SaveChanges();
return CreatedAtRoute("PostJobRoute", new { id = job.Id }, jobDetailList.AsEnumerable());
不过AW04是对的。 您可能希望实现DTO模式并将您的域投影到该模式中