Which code segment should you use?

You use Microsoft Visual Studio 2010 and Microsoft .NET Framework 4.0 to develop an application.
You use the ADO.NET Entity Framework Designer to model entities.
You need to associate a previously deserialized entity named person1 to an object context named model and persist changes to the database.
Which code segment should you use?

You use Microsoft Visual Studio 2010 and Microsoft .NET Framework 4.0 to develop an application.
You use the ADO.NET Entity Framework Designer to model entities.
You need to associate a previously deserialized entity named person1 to an object context named model and persist changes to the database.
Which code segment should you use?

A.
person1.AcceptChanges();
model.SaveChanges();

B.
model.People.ApplyChanges(person1) ;
model.SaveChanges();

C.
model.AttachTo(“People”, person1);
model.SaveChanges();

D.
model.People.Attach(person1);
model.SaveChanges();

Explanation:
Cosiderations from Attaching and Detaching objects (http://msdn.microsoft.com/en-us/library/bb896271.aspx):
* The object that is passed to the Attach method must have a valid EntityKey value. If the object does not have a valid EntityKey value, use the AttachTo method to specify the name of the entity set.

Attach Use the Attach method of ObjectContext where the method accepts a single typed entity parameter.
AttachTo The AttachTo method of ObjectContext accepts two parameters. The first parameter is a string containing the name of the entity set.
The second parameter type is object and references the entity you want to add.
Attach The Attach method of ObjectSet, which is the entity set type, accepts a single typed parameter containing the entity to be added to the ObjectSet.

CHAPTER 6 ADO.NET Entity Framework
Lesson 2: Querying and Updating with the Entity Framework
Attaching Entities to an ObjectContext(page 437)

Attaching and Detaching objects
(http://msdn.microsoft.com/en-us/library/bb896271.aspx)

http://msdn.microsoft.com/en-us/library/bb896248(v=vs.90).aspx
http://msdn.microsoft.com/en-us/library/bb896248.aspx



Leave a Reply 3

Your email address will not be published. Required fields are marked *


Mike

Mike

But Attach is a wrapper round the AttachTo method so D would do perfectly well.

Gaius

Gaius

You should also modify the entity state before calling SubmitChanges(), because after calling Attach/AttachTo, the state is Unmodified, and in this state, no changes are persisted.

Gaius

Gaius

I think AttachTo is probably more correct than Attach because we are not told that the entity model itself implements IEntityWithKey.

The EDM Designer could have code generation strategy set to off, or have a custom t4 template for generating entities, in which case the deserialized entity would not implement IEntityWithKey.