Home > other >  C# code not working as expected. Keep getting a bool variable as false
C# code not working as expected. Keep getting a bool variable as false

Time:01-06

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

CodePudding user response:

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.

CodePudding user response:

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);
}

CodePudding user response:

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.

  • Related