2

Possible Duplicate:
How to update a record without selecting that record again in ADO.NET Entity Framework?

i am working on a windows application which I need to show list of objects and its children in the grid. so user can modify the entity which are retrieved from the entity framework.

while updating the objects in the db, it looks like need to retrieve the object from db and assign the new values. This is may cause performance issue. is there work around for this?

    public class Vehicle
    {
        public Vehicle()
        {
            this.Fillups = new List<FillupEntry>();
            this.Reminders = new List<Reminder>();
        }
        public int VehicleId { get; set; }
        public int UserId { get; set; }
        public string Name { get; set; }
        public string ModelName { get; set; }
        public ICollection<FillupEntry> Fillups { get; set; }
        public ICollection<Reminder> Reminders { get; set; }
    }




        public void Update(Vehicle updatedVehicle)
        {
            Vehicle vehicleToUpdate =
                this.GetDbSet<Vehicle>()
                        .Where(v => v.VehicleId == updatedVehicle.VehicleId)
                        .First();

            vehicleToUpdate.Name = updatedVehicle.Name;
            vehicleToUpdate.Year = updatedVehicle.Year;
            vehicleToUpdate.MakeName = updatedVehicle.MakeName;
            vehicleToUpdate.ModelName = updatedVehicle.ModelName;
            vehicleToUpdate.SortOrder = updatedVehicle.SortOrder;
            vehicleToUpdate.PhotoId = updatedVehicle.PhotoId;

            this.SetEntityState(vehicleToUpdate, vehicleToUpdate.VehicleId == 0
                                                     ? EntityState.Added
                                                     : EntityState.Modified);
            this.UnitOfWork.SaveChanges();
        }
Community
  • 1
  • 1
Anand Kumar
  • 395
  • 2
  • 7
  • 18

1 Answers1

9

A good way to do this is with a thing i call dummy entities. This is when you attach a fake entitty to the graph with only a key in it. EF will only updte props you set after the update call.

So in your example:

Vehicle vehicleToUpdate = new Vehicle { VehicleId = updatedVehicle.VehicleId};
context.Vehicles.Attach(vehicleToUpdate);

vehicleToUpdate.Name = updatedVehicle.Name;
vehicleToUpdate.Year = updatedVehicle.Year;
vehicleToUpdate.MakeName = updatedVehicle.MakeName;
vehicleToUpdate.ModelName = updatedVehicle.ModelName;
vehicleToUpdate.SortOrder = updatedVehicle.SortOrder;
vehicleToUpdate.PhotoId = updatedVehicle.PhotoId;

context.SaveChanges();

you want to make sure you do this on a fresh context as attach will error if the entity is already tracked by the context.

undefined
  • 33,537
  • 22
  • 129
  • 198