Hello,
I have two tables - Student Table and Student address table and this tables having relation one to one and I want to write an Get and Put API for those two tables for fetching and updating data using Asp.Net Core using single ViewModels.
Student Table Columns-
StudentId, Name, MobileNo
Student Address Table Columns-
StudentId, Address, City.
Source Code-
- using System;
- using System.Threading.Tasks;
- using Bds.Api.AutoMapper;
- using Bds.Api.Models.Public;
- using Bds.Data.Models;
- using Bds.Service.Helpers;
- using Bds.Service.Interfaces;
- using Microsoft.AspNetCore.Authorization;
- using Microsoft.AspNetCore.Mvc;
- namespace Bds.Api.Controllers.Public.V1
- { [Route("api/v1/[controller]")]
- [Authorize]
- public class CoverController : Controller {
- private readonly IStudentService _studentService;
- private readonly IStudentAddressService _studentaadressService;
- public CoverController(IStudentService studentService, IStudentAddressService studentaadressService) {
- _studentService= studentService;
- _studentaadressService= studentaadressService; }
- [HttpGet("{id}")]
- public async Task<IActionResult> Get(int id) {
- try {
- var studModel = await _studentService.GetSingleByConditionAsync(u => u.StudentId== id);
- if (studModel == null) return BadRequest(ResponseMessages.GetErrorMessage(ResponseMessages.MessageType.NotFound));
- return Ok(studModel.ToSingle<StudentModel>());
- var studAddressModel = await _studentaadressService.GetSingleByConditionAsync(u => u.StudentId== id);
- if (studAddressModel == null) return BadRequest(ResponseMessages.GetErrorMessage(ResponseMessages.MessageType.NotFound));
- return Ok(studAddressModel.ToSingle<StudentAddressModel>());
- }
- catch (Exception ex)
- {
- return StatusCode(500, ResponseMessages.GetErrorMessage(ResponseMessages.MessageType.Fetch, ex.Message));
- }
- }
- [HttpPut("{id}")]
- public async Task<IActionResult> Put(int id, [FromBody]StudentModel studmodel, [FromBody]StudentAddressModel studaddmodel)
- {
- try {
- if (id == 0 || studmodel== null || studaddmodel==null)
- return BadRequest(ResponseMessages.GetErrorMessage(ResponseMessages.MessageType.InValid)); var response = await _studentService.UpdateAsync(model.ToSingle<Student>());
- var response = await _studentaadressService.UpdateAsync(model.ToSingle<StudentAddress>());
- return response > 0 ? Ok(ResponseMessages.GetSuccessMessage(ResponseMessages.MessageType.Edit)) : StatusCode(500, ResponseMessages.GetErrorMessage(ResponseMessages.MessageType.Edit));
- }
- catch (Exception ex) {
- return StatusCode(500, ResponseMessages.GetErrorMessage(ResponseMessages.MessageType.Edit, ex.Message));
- }
- }
- }
- }