-1

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'."

Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175
jmelero08
  • 7
  • 1
  • 5
    Well presumably `AddItem` is returning false because an exception is being thrown. If you were to *use* that exception (e.g. logging it) instead of just discarding the information and *just* returning `false`, you'd be able to tell what's wrong... (In general, catching exceptions without *at least* logging them is a bad idea, as it leaves you without any clue what's going wrong.) – Jon Skeet Jan 05 '23 at 18:06
  • As @JonSkeet said log your exception or at least tell us – Mike93041 Jan 05 '23 at 18:10

3 Answers3

0
public bool AddItem(Item newItem)
    {
        bool status = false;
        try
        {
            context.Items.Add(newItem);
            context.SaveChanges();
            status = true;
        }
        catch (Exception)
        {
            // Log the Exception here
            status=false;
        }
        return status;
    }

You need to log the exception instead of just discarding it and setting status to false.

I suspect you will find your problem there.

Sam
  • 15,336
  • 25
  • 85
  • 148
  • the Exception I am getting is "SqlException: String or binary data would be truncated in table 'OnlineFoodOrderDB.dbo.Items', column 'ItemId'. Truncated value: '123'." – jmelero08 Jan 05 '23 at 19:13
  • 1
    I think the value you are writing to the table exceeds your table definition for one of the fields. Eg if ItemId is a nvarchar(1) in the database, and you write "My Item" it would throw this error. Check your table definition in SQL or the Database you're using. – Zee Jan 05 '23 at 19:43
  • Thank you! turned out to be my input data and nothing with my code. – jmelero08 Jan 05 '23 at 20:22
0

AddItem() throws an exception. It would be helpful if you debug or display the exception that is thrown with for example the following code added:

try{
    ...
}catch(Exception ex) {
    Console.WriteLine(ex);
}
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jan 06 '23 at 01:57
0

According to the exception message you have shared, the problem is that you specify a value for ItemId which is longer than the maximum value supported by your schema.

Since it is truncated to 123, it is safe to assume that the type supports maximum 3 characters.

At the line of

context.Items.Add(newItem);

You could do the truncation yourself if that's what you want. But then, if you are to store '12345', then you will end up having '123'.

Alternatively, you could validate your value, like

[StringLength(3, ErrorMessage = "ItemId cannot be longer than 3 characters")]

Or, you could change your schema to change the type of ItemId in your database to allow it to hold a longer value, like:

ALTER TABLE yourtable VARCHAR(16);

Whatever you choose for your solution, it will be wise to make sure that you make sure that in the catch block of your try, you properly handle the Exception, logging it somewhere or showing it somehow, so the next time you have such a problem, you will have an easier time solving it.

Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175