Saturday, November 12, 2011

Bug [SaveProduct doesn't work] and solution for it in "Pro ASP.NET MVC 3 Framework" by Steven Sanderson, Adam Freeman

During reading "Pro ASP.NET MVC 3 Framework" by Steven Sanderson, Adam Freeman I found that my code doesn't working (Chapter 9, page 267). There is the Repository method called SaveChanges and it doesn't work for me. The code is defined like below:

public void SaveProduct(Product product) {
            if (product.ProductID == 0) {
                context.Products.Add(product);
            }
            context.SaveChanges();
        }
In order to get it working you need to change it:
public void SaveProduct(Product product)
        {
            if (product.ProductID == 0)
            {
                m_Context.Products.Add(product);
            }
            else
            {
                m_Context.Entry(product).State = System.Data.EntityState.Modified;
            }

            m_Context.SaveChanges();
        } 
Hope this would help others in learning MVC using this incredible book!

1 comment: