1

I am trying to add a Cart record into my class ProjectConext which is of type DbConext. The problem is that when I Add the record and try to save it, I get the error that the CustomerID field cannot be null (which it can't), even though as far as I can see I am inserting a non-null value for it. Here is my code for the Model:

    public class ShoppingCart
{
    ProjectContext _db = new ProjectContext();

    public void AddToCart(Video toAdd, Customer CurUser)
    {
        var CartItem = new Cart
        {
            CustomerID = CurUser.CustomerID,
            Item = toAdd.Title,
            Count = 1,
            Price = 1.00
        };
        _db.Carts.Add(CartItem);
        _db.SaveChanges();
    }
}

I inserted a breakpoint at the line after the Add() and I can see that CartItem has all fields filled, and _db.Carts is MVCProject.Model.Cart as it should be. If anyone has an idea of why this is not adding the record correctly your help would be greatly appreciated. Thanks in advance.

4
  • Can you post what your CartItem entity looks like? Specifically, the configuration. Commented Jan 31, 2013 at 2:23
  • What about the exception inner exception? Commented Jan 31, 2013 at 3:03
  • The inner exception I am getting is:"Cannot insert the value NULL into column 'CustomerID', table 'Azim.dbo.Carts'; column does not allow nulls. INSERT fails.\r\nThe statement has been terminated." My Cart looks like this:namespace MVCVideoProject.Models { public class Cart { [Key] public int CustomerID { get; set; } public string Item { get; set; } public int Count { get; set; } public double Price { get; set; } } } Commented Jan 31, 2013 at 13:50
  • Sorry about the formatting. I can see in my breakpoint after the Add() line that the record does in fact get inserted into my DbContext, so I don't understand why it is giving me this error. Commented Jan 31, 2013 at 13:51

1 Answer 1

1

I found the answer, the problem was that since CustomerID was an identity column in the Cart table, it was trying to automatically insert a value which erased the existing. Adding the code: DatabaseGenerated(DatabaseGeneratedOption.None)

as in

    public class Cart
{
    [Key, Required, DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int CustomerID { get; set; }
    public string Item { get; set; }
    public int Count { get; set; }
    public double Price { get; set; }
}

Solved the problem.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.