WebAPI从其他模型中返回Json

时间:2016-02-09 20:40:25

标签: c# json asp.net-web-api routes asp.net-web-api2

我可能写错了我的搜索但是我还没有找到任何与从控制器返回“更多”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"
            }]
        }]
    }
}

内容来自我在POST后的“JobsController”,您可以看到填充其他字段。

// 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”到“jobdetails”,但这不起作用。

1 个答案:

答案 0 :(得分:1)

您将返回传递给动作的对象,这就是原因。不要返回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模式并将您的域项目投射到