Crud implemented by Contact

This commit is contained in:
2023-04-19 17:25:42 +02:00
parent 0234db870b
commit ede368b963
10 changed files with 334 additions and 31 deletions

View File

@ -0,0 +1,87 @@
using BlazorSyncfusionCrm.Server.Data;
using BlazorSyncfusionCrm.Shared;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
namespace BlazorSyncfusionCrm.Server.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class ContactsController : ControllerBase
{
private readonly DataContext _context;
public ContactsController(DataContext context)
{
_context = context;
}
[HttpGet]
public async Task<ActionResult<List<Contact>>> GetAllContacts()
{
return await _context.Contacts
.Where(c => !c.IsDeleted)
.ToListAsync();
}
[HttpGet("{id}")]
public async Task<ActionResult<Contact>> GetContactById(int id)
{
var result = await _context.Contacts.FindAsync(id);
if (result == null)
{
return NotFound("Contact not found.");
}
return result;
}
[HttpPost]
public async Task<ActionResult<Contact>> CreateContact(Contact contact)
{
_context.Contacts.Add(contact);
await _context.SaveChangesAsync();
return Ok(contact);
}
[HttpPut("{id}")]
public async Task<ActionResult<Contact>> UpdateContact(int id, Contact contact)
{
var dbContact = await _context.Contacts.FindAsync(id);
if (dbContact == null)
{
return NotFound("Contact not found.");
}
dbContact.FirstName = contact.FirstName;
dbContact.LastName = contact.LastName;
dbContact.NickName = contact.NickName;
dbContact.DateOfBirth = contact.DateOfBirth;
dbContact.Place = contact.Place;
dbContact.DateUpdated = DateTime.Now;
await _context.SaveChangesAsync();
return Ok(contact);
}
[HttpDelete("{id}")]
public async Task<ActionResult<List<Contact>>> DeleteContact(int id)
{
var dbContact = await _context.Contacts.FindAsync(id);
if (dbContact == null)
{
return NotFound("Contact not found.");
}
dbContact.IsDeleted = true;
dbContact.DateDeleted = DateTime.Now;
await _context.SaveChangesAsync();
return await GetAllContacts();
}
}
}