I am trying to build this online food ordering app. while testing a HttpPost method in a controller using Postman, I am expecting a bool value of true, but keep getting the message that corresponds to it being false.
this is my WebService Model.
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace OnlineFoodOrderWebService.Models
{
public class Item
{
[Required]
public int CategoryId { get; set; }
[Required]
public string ItemId { get; set; }
[Required, StringLength(50, MinimumLength = 4)]
public string ItemName { get; set; }
[Required]
public decimal Price { get; set; }
}
}
this is my DAL model
using System;
using System.Collections.Generic;
#nullable disable
namespace OnlineFoodOrderDALCrossPlatform.Models
{
public partial class Item
{
public Item()
{
Orders = new HashSet<Order>();
}
public string ItemId { get; set; }
public string ItemName { get; set; }
public int CategoryId { get; set; }
public decimal Price { get; set; }
public virtual Category Category { get; set; }
public virtual ICollection<Order> Orders { get; set; }
}
}
this is the corresponding method from my repository.
public bool AddItem(Item newItem)
{
bool status = false;
try
{
context.Items.Add(newItem);
context.SaveChanges();
status = true;
}
catch (Exception)
{
status=false;
}
return status;
}
And this is my method from my controller class.
[HttpPost]
public JsonResult AddItem(Models.Item item)
{
bool status = false;
string message;
try
{
Item newItem = new Item
{
CategoryId = item.CategoryId,
ItemId = item.ItemId,
ItemName = item.ItemName,
Price = item.Price,
};
status = repository.AddItem(newItem);
if (status)
{
message = "Successful add of new Item";
}
else
{
message = "Failed to add new Item";
}
}
catch (Exception)
{
message = "Something went wrong, try again.";
}
return Json(message);
}
When I test in postman I should be getting back "Successful add of new Item" but keep getting "Failed to add new Item". I have tried a lot of different things with no luck. Any help would be great!
this is what I am posting on postman by the way
{
"CategoryId": 1,
"ItemId": "abc123",
"ItemName": "My Item",
"Price": 19.99
}
the Exception I am getting is
"SqlException: String or binary data would be truncated in table 'OnlineFoodOrderDB.dbo.Items', column 'ItemId'. Truncated value: '123'."