Entity Framework not saving changes
If you are after the insert/update functionality you have to cover both cases:
if (product.ProductID == 0)
{
context.Entry(product).State = EntityState.Added;
}
else
{
context.Entry(product).State = EntityState.Modified;
}
context.SaveChanges();
Thanks to @veblok I found the solution to my issue. There is an option in the DbContext class to prevent EF to track object by default. Once removed it EF started behaving as expected.
public class My Context : DbContext {
public MyContext()
{
// REMOVE this or use veblok's solution
this.Configuration.AutoDetectChangesEnabled = false;
}
...
}
you can use Create method of context : use this method generally when you have a related entity
public void SaveProduct(Product product)
{
if (product.ProductID == 0)
{
product = context.Products.Create();
product.property = ...;
product.property = ...;
context.Products.Add(product);
}
context.SaveChanges(); // Breakpoint here
}