0

I'm currently learning ASP.NET and having some problems. I have 2 tables related to each other by Foreign Key.
Employee.cs

public class Employee
    {
        [Key]
        public int EmployeeId { get; set; }
        [Column(TypeName = "nvarchar(50)")]
        [Required]
        public string EmployeeFullName { get; set; }
        [Required]
        [ForeignKey("DepartmentId")]
        public virtual Department EmployeeDepartment { get; set; }
    }

Department.cs

public class Department
    {
        [Key]
        public int DepartmentId { get; set; }
        [Column(TypeName = "nvarchar(10)")]
        [Required]
        public string DepartmentName { get; set; }
    }

I use the HTTP POST JSON and normally get values at both tables:

{
  "employeeId": 0,
  "employeeFullName": "string",
  "employeeDepartment": {
    "departmentId": 0,
    "departmentName": "string"
  }
}

But when I use the GET HTTP. I got:

[
  {
    "employeeId": 1,
    "employeeFullName": "string",
    "employeeDepartment": null
  }
]

How can I show the employeeDepartment as JSON instead. Like this:

[
  {
    "employeeId": 1,
    "employeeFullName": "string",
    "employeeDepartment":{
    "departmentId":1,
    "departmentName":"string"
    }
  }
]

I use the API Controller

[HttpGet("{id}")]
        public async Task<ActionResult<Employee>> GetEmployee(int id)
        {
            var employee = await _context.Employees.FindAsync(id);

            if (employee == null)
            {
                return NotFound();
            }

            return employee;
        }

How can I use http GET to receive just some specific fields? For example, I just want to get the EmployeeId with EmployeeFullName only.

1 Answer 1

1

Try this

public async Task<ActionResult<Employee>> GetEmployee(int id)
 {
 
var employee = await _context.Employees
             .Include(i=> i.EmployeeDepartment)
             .Where(i=> i.EmployeeId == id)
             .FirstOrDefaultAsync();

            if (employee == null)
            {
                return NotFound();
            }

            return Ok(employee);
        }

UPDATE

if you want to get just employee name try this

public async Task<ActionResult<string>> GetEmployee(int id)
 {

var employeeName = await _context.Employees
             .Where(i=> i.EmployeeId == id)
             .Select (i=> i.EmployeeFullName)
             .FirstOrDefaultAsync();

            if (employeeName == null)
            {
                return NotFound();
            }

            return Ok( employeeName);
}

or

public async Task<ActionResult> GetEmployee(int id)
 {

var employeeName = await _context.Employees
        .Where(i=> i.EmployeeId == id)
      .Select (i=>  new { EmployeeFullName= i.EmployeeFullName})
      .FirstOrDefaultAsync();
.....
 
// or maybe if you want it inside of array
public async Task<ActionResult<IEnumerable<Employee>>> GetEmployee(int id)
 {

var employeeName = await _context.Employees
        .Where(i=> i.EmployeeId == id)
       .Select (i=>  new Employee {
 EmployeeId=  i.EmployeeId,
 EmployeeFullName=  i.EmployeeFullName})
             .ToArrayAsync();

var employeeName = await _context.Employees
        .Where(i=> i.EmployeeId == id)
       .Select (i=>  new {
 EmployeeId=  i.EmployeeId,
 EmployeeFullName=  i.EmployeeFullName})
             .ToArrayAsync();

or maybe if you want an array of all employees

public async Task<ActionResult> GetAll()
 {
var employeeNames = await _context.Employees
   .Select (i=>  new Employee { 
  EmployeeId=  i.EmployeeId,
 EmployeeFullName=  i.EmployeeFullName})
             .ToArrayAsync();

//or just array of all employee names
var employeeNames = await _context.Employees
        .Select (i=> i.EmployeeFullName)
             .ToArrayAsync();

you can try all of them and select what you need

Sign up to request clarification or add additional context in comments.

7 Comments

Thanks! It works! Can I ask one another question? How can I show some specific fields only in http GET, like I want to post all the fields, but only get employeeFullName only for example. I'll update the question.
@ĐạtNguyễn I updated my answer pls check and let me know if it is what you want or I can make changes
Can I get it as an object? Like this: [ {"employeeFullName":"string"} ]
where do you have this error ? inside of the action? and what query have you selected? try Task<ActionResult<IEnumerable<Employee>>> or Task<ActionResult<Employee>> one of them should work
@ĐạtNguyễn And try to use return Ok(employee) or Ok(employeeName);
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.