Michel
Michel

Reputation: 23615

update disconnected object in entity framework

I have some data coming from other tiers and it represents an EF object. When it's new, I do this:

context.AddToCustomer(mynewobject);
context.SaveChanges();

but now my data forms an existing object, so I want the context to know I want to update the data and not inserting it.

I've seen 'ApplyPropertyChanges' but I can't figure out how to use it. I've also seen people doing this:

Customer existingOne = (from n in context.Customers 
                        where n.id = mynewobject.id select n).First()
existingOne.name = mynewobject.name
existingOne.address= mynewobject.address
context.SaveChanges();

but that seems a little odd because I have to manually set all the props AND read the entire object first.

Upvotes: 14

Views: 6416

Answers (4)

Andreas
Andreas

Reputation: 5631

In Entity Framework 5 this is how you go about:

        /// <summary>
        /// Updates an entity
        /// </summary>
        /// <param name="input">A entity</param>
        /// <returns>The updated object</returns>
        public TEntity Update(TEntity input)
        {
            using (var context = GetContext())
            {
                context.Set<TEntity>().Attach(input);

                var entry = context.ChangeTracker.Entries<TEntity>().FirstOrDefault(e => e.Entity == input);
                if (entry != null)
                    entry.State = EntityState.Modified;

                context.SaveChanges();
            }

            return input;
        }

Upvotes: 8

Craig Stuntz
Craig Stuntz

Reputation: 126547

While I question whether it's even worthwhile to "optimize" an update, you can nevertheless do what you ask. It's easier in EF 4, but also possible in EF 1. See also this article.

public static void AttachAsModified<T>(this ObjectSet<T> objectSet, T entity) where T : class
{
    objectSet.Attach(entity);
    objectSet.Context.ObjectStateManager.ChangeObjectState(entity, EntityState.Modified);
}

Upvotes: 4

Ashraf Alam
Ashraf Alam

Reputation: 3650

Taken from Employee Info Starter Kit, you can consider the code snippet as below:

public void UpdateEmployee(Employee updatedEmployee)
        {
            //attaching and making ready for parsistance
            if (updatedEmployee.EntityState == EntityState.Detached)
                _DatabaseContext.Employees.Attach(updatedEmployee);
            _DatabaseContext.ObjectStateManager.ChangeObjectState(updatedEmployee, System.Data.EntityState.Modified);
            _DatabaseContext.SaveChanges();
        }

Upvotes: 0

C&#233;dric Boivin
C&#233;dric Boivin

Reputation: 11351

There is on of my post to execute this

Upvotes: 0

Related Questions