Click here to Skip to main content
15,397,981 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
There are two entities Task and User. Task entity has two foreign keys (both int - id) Performer and Creator that is linked to User entity Id field. They are shadow properties, so in db their name are PerformerId and CreatorId. When I try to test POST request, Swagger shows Json structure like this and requires Creator not CreatorId:

{
  "id": 0,
  "name": "string",
  "description": "string",
  "status": 0,
  "creator": {
    "id": 0,
    "fullName": "string",
    "roleId": 0,
    "email": "user@example.com",
    "password": "string"
  },
  "performer": {
    "id": 0,
    "fullName": "string",
    "roleId": 0,
    "email": "user@example.com",
    "password": "string"
  }
}


The question is how to make program to get Json structure like this one, only IDs of foreig keys, not the every field:

{
      "name": "string",
      "description": "string",
      "status": 0,
      "creatorId": int,
      "performerId": int: 
}


That is how my Task model looks like:

C#
public class Task
{
    {
        public int Id { get; set; }

        public string Name { get; set; } = String.Empty;
        
        public string? Description { get; set; }

        public Statuses Status { get; set; }

        public User Creator { get; set; }

        public User? Performer { get; set; }
    }
    public enum Statuses
    {
        NotStarted,
        Completed
    }
}


And there is my POST request from controller:
C#
[HttpPost]
public IActionResult CreateTask([FromBody] Data.Entities.Task task)
{
  if (task == null)
  {
     return BadRequest();
  }
            
  _context.Tasks.Add(task);
  _context.SaveChanges();

  return CreatedAtRoute("GetTaskById", new { id = task.Id }, task);
}


What I have tried:

Tried to configure in model itself.
Posted
Comments
Gerry Schmitz 14-Jun-22 16:50pm
   
The JSON reflects your model; which is simply wrong for what you're asking of it.

https://www.entityframeworktutorial.net/code-first/configure-one-to-one-relationship-in-code-first.aspx

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900