I have the following problem when updating objects. Below is my WCF method. (The update is called by the public Save method after determining whether it is updated or added)
protected bool UpdateSalesMaster(SalesMaster order) { using (var context = new MyContext()) { SalesMaster original = context.SalesMasters.FirstOrDefault(o => o.OrderID == order.OrderID); if (original != null) { context.Entry(original).CurrentValues.SetValues(order); foreach (SalesDetail detail in order.SalesDetails) { if (detail.OrderDetailID == 0) context.SalesDetails.Add(detail); else { SalesDetails originalDetail = context.SalesDetails.FirstOrDefault(o => o.OrderDetailID == detail.OrderDetailID); if (originalDetail != null) context.Entry(originalDetail).CurrentValues.SetValues(detail); } } context.SaveChanges(); return true; } else { throw new FaultException(string.Format("Invalid Order specified: {0}", order.OrderID)); } } }
When I simply update OrderDate in SalesMaster and do not change it in detail, the update request is updated in the database for details. I was expecting to see an Update request only for SalesMaster.
Can someone tell me what I'm doing wrong here? I do not want to run update requests in the database if nothing has changed.
I use the approach of getting the original value from the database to determine if any values ββare updated using context.Entry (originalDetail) .CurrentValues.SetValues ββ(detail);
I also override SaveChanges to set the LastModified date by checking for IAuditable object implementation. This is when I find that the state of the part part is identified as changed. But the only update that happens in the database is LastModifiedBy, which was updated in my save changes. I'm not sure how he was set up for the modification state when nothing changed in detail.
public override int SaveChanges() { var changeSet = ChangeTracker.Entries<IAuditable>(); if (changeSet != null) { foreach (var entry in changeSet.Where(c => c.State != EntityState.Unchanged)) { if (entry.State == EntityState.Added) entry.Entity.DateCreated = DateTime.Now; if (entry.State == EntityState.Modified) { entry.Property(a => a.CreatedByUser).IsModified = false; entry.Property(a => a.DateCreated).IsModified = false; } entry.Entity.DateModified = DateTime.Now; } } try { return base.SaveChanges(); } catch (DbEntityValidationException ex) { throw ex; } }
My solution structure:
- Client - Windows Forms User Interface
- Entities - POCO as a standalone library
- WCF - all business logic, adding, updating, deleting objects.
- Data Context - Entity Framework with Fluent mapping.
source share