Failed to insert data into the database

Viewed 190

First, I pick data from the session. and these data I trying to transfer to another model. but is my first data(session) is uploaded successfully into the database.first data transfer is successful. but the second third fourth whatever, those data can't transfer my model.

Here is my code:

public async Task<IActionResult> Checkout(Order11 anOrder) {
    List<Shop> shop = HttpContext.Session.Get<List<Shop>>("shop");

    for (int i = 0; i < shop.Count(); i++) {
        if (shop != null) {
            anOrder.ProductName = shop[i].Name;
            anOrder.ImagePath = shop[i].Image;
            anOrder.Price = shop[i].Price;
            anOrder.Quantity = shop[i].Quantity;

            anOrder.OrderNo = GetOrderNo();

            _db.Order11.Add(anOrder);
        }

        _db.SaveChanges();
    }

    // other code
}

Order11.cs

  public class Order11
    {
        public int Id { get; set; }
        [Display(Name = "Order Number")]
        public string OrderNo { get; set; }
        [Required]
        public string Name { get; set; }
        [Required]
        [Display(Name = "Phone Number")]
        public string PhoneNo { get; set; }
        [Required]
        [EmailAddress]
        public string Email { get; set; }
        [Required]
        public string Address { get; set; }

        public DateTime OrderDate { get; set; }
        public string ImagePath { get; set; }

        public int Quantity { get; set; }

        public int Price { get; set; }
        public string ProductName { get; set; }

    }
}

When I run the application then I get this error:

enter image description here

I want to transfer all sessions data into my model(DB). What's the solution to this problem? I am a beginner please help.

2 Answers

Please Set anOrder.Id = 0; before saving the data.

Show please inner exception using try, catch. I cannot comment.

public async Task<IActionResult> Checkout(Order11 anOrder)
{
List<Shop> shop = HttpContext.Session.Get<List<Shop>>("shop");

for (int i = 0; i < shop.Count(); i++)
{
    try
    {
    if (shop != null)
    {
        anOrder.ProductName = shop[i].Name;
        anOrder.ImagePath = shop[i].Image;
        anOrder.Price = shop[i].Price;
        anOrder.Quantity = shop[i].Quantity;

        anOrder.OrderNo = GetOrderNo();

        _db.Order11.Add(anOrder);
    }

    _db.SaveChanges();
    }
    catch(Exception ex)
    {
    }
}

// other code
}
Related