DbContext.SaveChanges Method Throw null reference exception while saving data

asp.net c# entity-framework-6

Question

Am using EF 6.0 for my web application, whenever i tried to save or update data via EF, it throws a "null reference exception".. this method is responsible for creating products

private Product createProduct()
{
    Product product = new Product();
    product.Name = txtName.Text;
    product.Price = Convert.ToInt32(txtPrice.Text);
    product.ProductTypeId = Convert.ToInt32(ddlType.SelectedValue);
    product.Desciption = txtDesciption.Text;
    product.Image = ddlImage.SelectedValue;
    return product;
}

this method is calling "insert product method"

protected void btnSubmit_Click(object sender, EventArgs e)
{
    ProductModel model = new ProductModel();
    Product product = createProduct();
    lblStatus.Text = model.InsertProduct(product);
}

This method is performing "product insertion function" and it throws exception

public string InsertProduct(Product product)
{
    try
    {
        PizzaHuttSliceEntities db = new PizzaHuttSliceEntities();
        db.Products.Add(product);
        db.SaveChanges();
        return product.Name + "was successfully inserted! ";
    }
    catch (Exception e)
    {
        return "Error: " + e;
    }
}

Here is product class

public partial class Product
{
    public Product()
    {
        this.Carts = new HashSet<Cart>();
    }

    public int ID { get; set; }
    public int ProductTypeId { get; set; }
    public string Name { get; set; }
    public int Price { get; set; }
    public string Desciption { get; set; }
    public string Image { get; set; }

    public virtual ICollection<Cart> Carts { get; set; }
    public virtual ProductType ProductType { get; set; }
}

Here is Trace Info

enter image description here

1
1
4/19/2016 5:34:09 PM

Popular Answer

Solved! Actually the problem is with ddlType DataSource, i just refresh the schema of SqlDataSource for ddlType and the problem vanished. Because i did an update to the database and that's why the ddlType pointing to such reference which wasn't exist anymore and for this reason DbContext.SaveChanges method throwing null reference exception Thanks to all who pay attention to my question

1
4/20/2016 4:20:33 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow