Trackable entities

Apr 30, 2015 at 5:01 PM
Edited Apr 30, 2015 at 5:02 PM
Hi,

I have this entity:
 public class Order:Entity
    {
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        [Key]
        public Guid Id { get; set; }

        public virtual int? DeliveryTypeId { get; set; }
       public virtual int? PaymentOrderId { get; set; }
        public virtual decimal DeliveryPrice { get; set; }

        [ForeignKey("PaymentOrderId")]
        public virtual PaymentOrder PaymentOrder { get; set; }

        [InverseProperty("Order")] 
        public virtual ICollection<PaymentOrder> PaymentOrders { get; set; }
    }
The context has ProxyCreation enabled
this.Configuration.ProxyCreationEnabled = true;
And i'm trying to update these fields on the following way:
            var orderRepository = _unitOfWorkAsync.Repository<Order>();
            var order = orderRepository.Find(orderId);

            order.DeliveryTypeId = formData.DeliveryType;
            order.PaymentOrder = paymentOrder;
            order.DeliveryPrice = 11;

            orderRepository.Update(order);
           _unitOfWorkAsync.SaveChanges();
SaveChanges is updating all the fields in the entity. What do i have to do so that i only update the columns where i changed the value?

Thanks
Apr 30, 2015 at 5:10 PM
SaveChanges always updating all the fields, it's normal behavier. You have that give an object with all the fields filled for the methods, ok?

PS.: Sorry by English.
Apr 30, 2015 at 5:37 PM
Edited Apr 30, 2015 at 5:38 PM
AlanBessa wrote:
SaveChanges always updating all the fields, it's normal behavier. You have that give an object with all the fields filled for the methods, ok?

PS.: Sorry by English.
No, it is not supposed to be like that. If you have the Entity attached to your context, having ProxyCreationEnabled and your properties marked as virtual, your context knows which properties were changed ( check ChangeTracker on your context).

Anyway, my solution was:
  • Not calling Update ( as it marks the Entity as Modified )
  • Add an extra ObjectState ( DetectChanges )
  • Mark the entity with ObjectState = ObjectState.DetectChanges;
  • Change SyncObjectsStatePreCommit to:
 private void SyncObjectsStatePreCommit()
        {
            foreach (var dbEntityEntry in ChangeTracker.Entries())
            {
                var objectState = ((IObjectState) dbEntityEntry.Entity).ObjectState;

                if (objectState != ObjectState.DetectChanges)
                    dbEntityEntry.State = StateHelper.ConvertState(((IObjectState)dbEntityEntry.Entity).ObjectState);
            }
        }
  • Call SaveChanges() ( where this returns 2, as the number of changes made );
If anyone has a better solution please tell me!

Thanks
Marked as answer by lelong37 on 5/12/2015 at 9:35 AM