entity-framework-4objectset

EF4 ObjectContext.Attach Question?


If I construct an object like say, Category, assign the values to the properties, one being the ID that is the same as a row in the database and pass it to the ObejctSet.Attach method and call the SaveChanges on the Context, will it update that row in the database? Or does the entity have to be retrieved first?


Solution

  • Both scenarios are possible. The difference is if you work with attached or detached instance.

    You can create object, attach it to context, say to context that object is modified (attaching marks object as unchanged) and save changes.

    Or

    You can load object from context, modify object, save changes on the same context (you don't need to set it as modified because object context track changes for objects it loaded).

    I wrote examples for both scenarios here.