Oluwatobi Akinseye
Oluwatobi Akinseye

Reputation: 46

context.SaveChanges() not updating data in SqlServer database

When I call context.SaveChanges() to update a specific product, the update is not registered in the database. I do not get any runtime error either. All I notice is that my product catalog is not updated. I still see the same values. When I run the debugger I notice that the connection state of the database is closed.

This is the class implementing the context.SaveChanges()

namespace SportsStore.Domain.Concrete
{
   public class EFProductRepository : IProductRepository
   {
       private EFDbContext context = new EFDbContext();

       public IQueryable<Product> Products
       {
           get { return context.Products; }
       }

       public void SaveProduct(Product product)
       {
           if (product.ProductID == 0)
           {
               context.Products.Add(product);
           }

           context.SaveChanges();
       }
   }
 }

namespace SportsStore.Domain.Concrete
{
   public  class EFDbContext : DbContext
   {
     public DbSet<Product> Products { get; set; }
   }
}

namespace SportsStore.Domain.Entities
{
    public class Product
    {

      [HiddenInput(DisplayValue=false)]
      public int ProductID { get; set; }

      public string Name { get; set; }

      [DataType(DataType.MultilineText)]
      public string Description { get; set; }

      public string Category { get; set; }

      public decimal Price { get; set; }
    }
}

Upvotes: 2

Views: 2174

Answers (1)

Mano Paul
Mano Paul

Reputation: 21

In the EFProductRepository class, prior to calling the context.SaveChanges() method in the SaveProduct method, you can use one of the following approaches to persist changes to the database.

public void SaveProduct(Product product)
{
    if (product.ProductID == 0)
    {
       context.Products.Add(product);
    }
    //One approach to persist changes to database
    //var productInDB = context.Products.Single(x => x.ProductID ==product.ProductID);
    //context.Entry(productInDB).CurrentValues.SetValues(product);
    //context.SaveChanges();

    //Alternate Approach
    if (product.ProductID != 0)
    {
       context.Entry(product).State = System.Data.EntityState.Modified;
    }
    context.SaveChanges();
}

Upvotes: 2

Related Questions