Home > OS >  How to implement get by id in ASP.NET Core Web API?
How to implement get by id in ASP.NET Core Web API?

Time:01-11

While I am trying to implement get by id API service I am getting all the records rather than one particular record in ASP.NET Core Web API.

[HttpGet("EmployeeId")]
public ActionResult<Employeedatum> Getbyid(int EmployeeId)
{
    if (EmployeeId <= 0)
    {
        return NotFound("not found");
    }

    Employeedatum employeedata = DbContext.Employeedatum.FirstOrDefault(s => s.empid == EmployeeId);

    if (employeedata == null)
    {
        return NotFound("notfound");
    }

    return Ok(employeedata);
}

enter image description here

DbContext:

public class ApplicationDbContext : DbContext
    {
        public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
        {
        }
       
        public DbSet<Employeedatum> Employeedata { get; set; }
     


        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Employeedatum>().ToTable("Employees");
        }
    }

Note: I have tried to reproduce your issue quickly thus I am using this DbFirst approach. But you can use, FluentAPI or Or any other pattern as well.

Controller:

    [Route("api/[controller]")]
    [ApiController]
    public class EmployeeController : ControllerBase
    {
        private readonly ApplicationDbContext _appDbContext;


        public EmployeeController(ApplicationDbContext appDbContext)
        {
            _appDbContext = appDbContext;
        }

        [HttpGet("Getbyid")]
        public ActionResult<Employeedatum> Getbyid(int EmployeeId)
        {
            if (EmployeeId <= 0)
            {
                return NotFound("not found");
            }

            Employeedatum employeedata = _appDbContext.Employeedata.FirstOrDefault(s => s.Id == EmployeeId);

            if (employeedata == null)
            {
                return NotFound("notfound");
            }

            return Ok(employeedata);
        }
       

    }

Output in postman:

enter image description here

CodePudding user response:

Try this as a Lync query

Employeedatum employeedata = DbContext.Employeedatum.where(s => s.empid == EmployeeId).FirstOrDefault();
  • Related