I created a webapi by looking at the ms basic documentation.
ms Doc
it was work
todoitems
Besides todoitems I
Because I wanted to use it in the form of Avatar Chart
Insert the model Avatarchart, create Avatarchartcontext, and make the controller as a scaffold.
solution view
However, when I tried to receive data as a post, the data always came in null.
error
null
this is code
[Route("api/AvatarCharts")]
[ApiController]
public class AvatarChartsController : ControllerBase
{
private readonly AvatarChartContext _context;
public AvatarChartsController(AvatarChartContext context)
{
_context = context;
}
// GET: api/AvatarCharts
[HttpGet]
public async Task<ActionResult<IEnumerable<AvatarChart>>> GetAvatarCharts()
{
return await _context.AvatarCharts.ToListAsync();
}
// GET: api/AvatarCharts/5
[HttpGet("{modelId}")]
public async Task<ActionResult<AvatarChart>> GetAvatarChart(long modelId)
{
var avatarChart = await _context.AvatarCharts.FindAsync(modelId);
if (avatarChart == null)
{
return NotFound();
}
return avatarChart;
}
// PUT: api/AvatarCharts/5
// To protect from overposting attacks, see https://go.microsoft.com/fwlink/?linkid=2123754
[HttpPut("{modelId}")]
public async Task<IActionResult> PutAvatarChart(long modelId, AvatarChart avatarChart)
{
if (modelId != avatarChart.modelId)
{
return BadRequest();
}
_context.Entry(avatarChart).State = EntityState.Modified;
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!AvatarChartExists(modelId))
{
return NotFound();
}
else
{
throw;
}
}
return NoContent();
}
// POST: api/AvatarCharts
// To protect from overposting attacks, see https://go.microsoft.com/fwlink/?linkid=2123754
[HttpPost]
public async Task<ActionResult<AvatarChart>> PostAvatarChart( AvatarChart avatarChart)
{
_context.AvatarCharts.Add(avatarChart);
await _context.SaveChangesAsync();
return CreatedAtAction("GetAvatarChart", new { modelId = avatarChart.modelId }, avatarChart);
}
// DELETE: api/AvatarCharts/5
[HttpDelete("{modelId}")]
public async Task<IActionResult> DeleteAvatarChart(long modelId)
{
var avatarChart = await _context.AvatarCharts.FindAsync(modelId);
if (avatarChart == null)
{
return NotFound();
}
_context.AvatarCharts.Remove(avatarChart);
await _context.SaveChangesAsync();
return NoContent();
}
private bool AvatarChartExists(long modelId)
{
return _context.AvatarCharts.Any(e => e.modelId == modelId);
}
}
public class AvatarChartContext :DbContext
{
public AvatarChartContext(DbContextOptions<AvatarChartContext> options) : base(options)
{
}
public DbSet<AvatarChart> AvatarCharts { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<AvatarChart>().HasKey(c => c.modelId);
}
}
public class AvatarChart
{
[Key]
public long modelId;
public string colorCode;
public long dateTime; //ex 20210101130000
public string name;
public string diagnose;
}
swagger
add postgressql dbenter image description here
Update:
You missed the {get; set;}.
public class AvatarChart
{
[Key]
public long modelId {get; set;}
public string colorCode {get; set;}
public long dateTime {get; set;} //ex 20210101130000
public string name {get; set;}
public string diagnose {get; set;}
}
Can you make these changes and tell me what value is being returned on the variable result. Also, can you validate your ModelState first?
[HttpPost]
public async Task<ActionResult> PostAvatarChart( AvatarChart avatarChart)
{
await _context.AvatarCharts.AddAsync(avatarChart);
var result = await _context.SaveChangesAsync() > 0;
return CreatedAtAction("GetAvatarChart", new { modelId = avatarChart.modelId }, avatarChart);
}
Related
I am using asp.net core 6 web api ,entity framework code first and CQRS - Mediatr for a project which has functinalities to update database and get data from database and show it in the swaggerui but I came across with a problem when I try to create a handler for the update data by its ID in the database I get this error :
Error CS0311 The type 'EnocaChallengeV2.Commands.UpdateFirmDateCommand' cannot be used as type parameter 'TRequest' in the generic type or method 'IRequestHandler<TRequest, TResponse>'. There is no implicit reference conversion from 'EnocaChallengeV2.Commands.UpdateFirmDateCommand' to 'MediatR.IRequest<int>'.
This is my Command:
using EnocaChallengeV2.Models;
using MediatR;
namespace EnocaChallengeV2.Commands
{
public class UpdateFirmDateCommand : IRequest<Firm> {
public int Id { get; set; }
public DateTime startTime { get; set; }
public DateTime endTime { get; set; }
public UpdateFirmDateCommand(int id, DateTime StartTime, DateTime EndTime)
{
Id = id;
startTime = StartTime;
endTime = EndTime;
}
}
}
This is the Handler:
using EnocaChallengeV2.Commands;
using EnocaChallengeV2.Models;
using EnocaChallengeV2.Queries;
using EnocaChallengeV2.Repositories;
using MediatR;
namespace EnocaChallengeV2.Handlers
{
public class UpdateFirmDateHandler : IRequestHandler<UpdateFirmDateCommand, int>
{
private readonly IFirmRepository _firmRepository;
public UpdateFirmDateHandler(IFirmRepository firmRepository)
{
_firmRepository = firmRepository;
}
public async Task<int> Handle(UpdateFirmDateCommand command, CancellationToken cancellationToken)
{
var firm = await _firmRepository.GetFirmByIdAsync(command.Id);
if (firm == null)
return default;
firm.startTime = command.startTime;
firm.endTime = command.endTime;
return await _firmRepository.UpdateFirmDateAsync(firm);
}
}
}
This is the interface:
using EnocaChallengeV2.Models;
namespace EnocaChallengeV2.Repositories
{
public interface IFirmRepository
{
public Task<List<Firm>> GetFirmListAsync();
public Task<Firm> GetFirmByIdAsync(int Id);
public Task<Firm> AddFirmAsync(Firm firm);
public Task<int> UpdateFirmDateAsync(Firm firm);
public Task<int> UpdateFirmVerificationAsync(Firm firm);
}
}
This is the repository:
using EnocaChallengeV2.Data;
using EnocaChallengeV2.Models;
using Microsoft.EntityFrameworkCore;
namespace EnocaChallengeV2.Repositories
{
public class FirmRepository : IFirmRepository
{
private readonly DbContextClass _dbContext;
public FirmRepository(DbContextClass dbContext)
{
_dbContext = dbContext;
}
public async Task<Firm> AddFirmAsync(Firm firm)
{
var result = _dbContext.Firms.Add(firm);
await _dbContext.SaveChangesAsync();
return result.Entity;
}
public async Task<int> DeleteFirmAsync(int Id)
{
var filteredData = _dbContext.Firms.Where(x => x.Id == Id).FirstOrDefault();
_dbContext.Firms.Remove(filteredData);
return await _dbContext.SaveChangesAsync();
}
public async Task<Firm> GetFirmByIdAsync(int Id)
{
return await _dbContext.Firms.Where(x => x.Id == Id).FirstOrDefaultAsync();
}
public async Task<List<Firm>> GetFirmListAsync()
{
return await _dbContext.Firms.ToListAsync();
}
public async Task<int> UpdateFirmDateByIdAsync(Firm firm)
{
_dbContext.Firms.Update(firm);
return await _dbContext.SaveChangesAsync();
}
//public async Task<Firm> UpdateFirmVerificationAsync(Firm firm)
//{
// _dbContext.Firms.Update(firm);
// return await _dbContext.SaveChangesAsync();
//}
}
}
I tried to change the Task<> to Firm and then to int but didn't seem to work.
You command needs to define a return type of 'int':
namespace EnocaChallengeV2.Commands
{
public class UpdateFirmDateCommand : IRequest<int> {
public int Id { get; set; }
public DateTime startTime { get; set; }
public DateTime endTime { get; set; }
public UpdateFirmDateCommand(int id, DateTime StartTime, DateTime EndTime)
{
Id = id;
startTime = StartTime;
endTime = EndTime;
}
}
}
Note the change:
IRequest<int>
I am trying to query the Product object from the database by using the ID. However, there was no data being sent to the View. I suspect that there is a problem with my Services and ProductController. I have try to use different methods to query the data
in the ProductServices file but none of them seems to work. Currently I don't know where the problem is.
Below is my code for the ProductService
using Microsoft.EntityFrameworkCore;
namespace e_commerce.Data.Services
{
public class ProductService : IProductService
{
private readonly ShopDbContext _context;
public ProductService(ShopDbContext context)
{
_context = context;
}
public void AddProduct(Product product)
{
_context.Products.Add(product);
_context.SaveChanges();
}
public IEnumerable<Product> GetProducts()
{
return _context.Products.ToList();
}
public void RemoveProduct(Product product)
{
throw new NotImplementedException();
}
public Product UpdateProduct(Product product)
{
throw new NotImplementedException();
}
public Product GetProductById(int id)
{
return _context.Products.FirstOrDefault(x => x.ProductID == id);
}
}
}
Here is my code for ProductController
using e_commerce.Data.Services;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
namespace e_commerce.Controllers
{
public class ProductController : Controller
{
private readonly IProductService _service;
public ProductController(IProductService service)
{
_service = service;
}
public ActionResult Index()
{
return View(_service.GetProducts());
}
public ActionResult Create()
{
return View();
}
[HttpPost]
public IActionResult Create([Bind("ProductImageUrl, ProductName, ProductPrice")]Product product)
{
if (ModelState.IsValid)
{
return View(product);
}
_service.AddProduct(product);
return RedirectToAction(nameof(Index));
}
public IActionResult Details(int id)
{
var products = _service.GetProductById(id);
return View();
}
}
}
Thank you for your help.
the problem is that you are not passing data with a view
public IActionResult Details(int id)
{
var product = _service.GetProductById(id);
if (product==null) product= new Product();
return View(product);
}
Here is my code and I want to create API, from the repository methods.
This is Entity table of my code:
public partial class Course
{
public int ID { get; set; }
public string Name { get; set; }
public int DepartmentID { get; set; }
[ForeignKey("DepartmentID")]
public virtual Department Department { get; set; }
public int GradeLevelsID { get; set; }
[ForeignKey("GradeLevelsID")]
public virtual GradeLevels GradeLevels { get; set; }
// Navigation
public virtual ICollection<Units> Units { get; set; }
}
I need some output according to the methods:
Create course for the particular Gradelevel
Get Course of the GradeLevel
Get All Unit of the course
I write code for the following condition in the IRepository
Public interface ICourseRepository
{
Task<Course> GetAllCourseByGradeLevleId(int id)
Task<Course> UpdateCoursetAsync(int Id);
Task<Action> CreateCourseAsync(Course Course);
Task<Course> DeleteCourseAsync(int Id);
}
And the Repository Methods will be as following:
public class CountryRepository : ICourseRepository
{
public Task<Action> CreateCourseAsync(Course Course)
{
throw new NotImplementedException();
}
public Task<Course> DeleteCourseAsync(int Id)
{
throw new NotImplementedException();
}
public Task<Course> GetAllCourseByGradeLevleId(int id)
{
throw new NotImplementedException();
}
public Task<Course> UpdateCoursetAsync(int Id)
{
throw new NotImplementedException();
}
My Problem is that I am unable to write return type method and unable to fetch data from the relational table, as well as unable to write POST and PUT api for this conditions.
Here is my controller class:
[Route("api/[controller]")]
[ApiController]
public class CourseController : ControllerBase
{
private readonly ICourseRepository _courseRespository;
public CourseController(ICourseRepository courseRespository)
{
_courseRespository = courseRespository;
}
[HttpGet]
public async Task<IEnumerable<Course>> Get()
{
return await _courseRespository.GetAllCourseAsync();
}
public async Task<ActionResult<Course>> GetId(int id)
{
var result = await _courseRespository.GetAllCourseByIdAsync(id);
if (result == null)
{
return NotFound();
}
return result;
}
[HttpPost]
public async Task<ActionResult> Post(Course course)
{
// _courseRespository.CreateCourseAsync();
// await _courseRespository.SaveChangesAsync();
return CreatedAtAction("GetId", new { id = course.ID }, course);
}
How can write PUT and POST in this condition.
Try having a code like below,
[Route("Course")]
public class CountryRepository : ICourseRepository
{
[Route("~/users/Create")]
[ResponseType(typeof(Course))]
[HttpPost]
public async Task<Action> CreateCourseAsync(Course Course)
{
return Request.CreateResponse(HttpStatusCode.OK, resultObj);
}
}
Ninject implementation works perfectly in WebForms. But due to some reasons it does not work in ashx.
My Code is below.
public class AllPlayers : HttpTaskAsyncHandler
{
[Inject]
public IUser _user { get; set; }
public AllPlayers(IUser user)
{
_user = user;
}
public AllPlayers()
{
}
public override async Task ProcessRequestAsync(HttpContext context)
{
var data = await _user.GetAllPlayers();
}
public bool IsReusable
{
get
{
return false;
}
}
}
Am I missing something ?
I'am working with TFS for the First time,I have created a restful web service with ASP.net the problem is that the navigator doesn't show me the data that it is stored in dataBase,per example:
var Subjects = new List<Subject>
{
new Subject{Libel="Sub1"},
new Subject{Libel="Sub2"},
new Subject{Libel="Sub3"},
new Subject{Libel="Sub4"},
};
Subjects.ForEach(s =>
{
s.ObjectState = Repository.Pattern.Infrastructure.ObjectState.Added;
context.Subjects.Add(s);
context.SaveChanges();
});
this model will intialize data into database,so I can see data in the database table Subject but not in the web service
any Help please
thanks
UPDate:
this is the model file:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SMA.Entities.Models
{
public partial class Subject : BaseEntity
{
public string Libel { get; set; }
public virtual List<SubjectLevel> SubjectLevels { get; set; }
public Subject()
{
SubjectLevels = new List<SubjectLevel>();
}
}
}
this is the model file for the SubjectLevel Entity:
public partial class SubjectLevel : BaseEntity
{
public int Coef { get; set; }
[ForeignKey("SubjectId")]
public virtual Subject Subject { get; set; }
public Int64 SubjectId { get; set; }
[ForeignKey("LevelId")]
public virtual Level Level { get; set; }
public Int64 LevelId { get; set; }
public virtual List<Schedule> Schedules { get; set; }
public SubjectLevel()
{
Schedules = new List<Schedule>();
}
The Subject Controller:
public class SubjectController : ODataController
{
private readonly ISubjectService _SubjectService;
private readonly IUnitOfWorkAsync _unitOfWorkAsync;
public SubjectController(
IUnitOfWorkAsync unitOfWorkAsync,
ISubjectService SubjectService)
{
_unitOfWorkAsync = unitOfWorkAsync;
_SubjectService = SubjectService;
}
// GET: odata/Subjects
[HttpGet]
[Queryable]
public IQueryable<Subject> GetSubject()
{
var l= _SubjectService.Queryable().ToList();
return _SubjectService.Queryable();
}
// GET: odata/Subjects(5)
[Queryable]
public SingleResult<Subject> GetSubject([FromODataUri] Int64 key)
{
return SingleResult.Create(_SubjectService.Queryable().Where(t => t.Id == key));
}
// PUT: odata/Subjects(5)
public async Task<IHttpActionResult> Put(Int64 key, Subject Subject)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
if (key != Subject.Id)
{
return BadRequest();
}
Subject.ObjectState = ObjectState.Modified;
_SubjectService.Update(Subject);
try
{
await _unitOfWorkAsync.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!SubjectExists(key))
{
return NotFound();
}
throw;
}
return Updated(Subject);
}
// POST: odata/Subjects
public async Task<IHttpActionResult> Post(Subject Subject)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
Subject.ObjectState = ObjectState.Added;
_SubjectService.Insert(Subject);
try
{
await _unitOfWorkAsync.SaveChangesAsync();
}
catch (DbUpdateException)
{
if (SubjectExists(Subject.Id))
{
return Conflict();
}
throw;
}
return Created(Subject);
}
//// PATCH: odata/Subjects(5)
[AcceptVerbs("PATCH", "MERGE")]
public async Task<IHttpActionResult> Patch([FromODataUri] Int64 key, Delta<Subject> patch)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
Subject Subject = await _SubjectService.FindAsync(key);
if (Subject == null)
{
return NotFound();
}
patch.Patch(Subject);
Subject.ObjectState = ObjectState.Modified;
try
{
await _unitOfWorkAsync.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!SubjectExists(key))
{
return NotFound();
}
throw;
}
return Updated(Subject);
}
// DELETE: odata/Subjects(5)
public async Task<IHttpActionResult> Delete(string key)
{
Subject Subject = await _SubjectService.FindAsync(key);
if (Subject == null)
{
return NotFound();
}
Subject.ObjectState = ObjectState.Deleted;
_SubjectService.Delete(Subject);
await _unitOfWorkAsync.SaveChangesAsync();
return StatusCode(HttpStatusCode.NoContent);
}
private bool SubjectExists(Int64 key)
{
return _SubjectService.Query(e => e.Id == key).Select().Any();
}
}
The view:
<h4>Subjects</h4>
(GET => api/Subjects) GetAll ยป<br />