PrepAway - Latest Free Exam Questions & Answers

What should you do?

You are adding a process to the application. The process performs the following actions:
1. Opens a ContosoEntities context object named context1.
2. Loads a Part object into a variable named part1.
3. Calls the Dispose() method on context1.
4. Updates the data in part1.
5. Updates the database by using a new ContosoEntities context object named context2.

You need to update the database with the changed data from part1. What should you do?

PrepAway - Latest Free Exam Questions & Answers

A.
Add the following code segment before calling SaveChanges() on context2:
context2.ApplyCurrentValues(“Parts”, part1);

B.
Add the following code segment before calling SaveChanges() on context2:
context2.Attach(part1);
context2.ApplyCurrentValues(“Parts”, part1);

C.
Add the following code segment before calling SaveChanges() on context2:
context2.Attach(part1);
context2.ObjectStateManager.ChangeObjectState(part1, System.Data.EntitySate.Modified);

D.
Add the following code segment before calling SaveChanges() on context2:
context2.ApplyOriginalValues(“Parts”, part1);

Explanation:
How to: Apply Changes Made to a Detached Object
(http://msdn.microsoft.com/en-us/library/bb896248.aspx)

private static void ApplyItemUpdates(SalesOrderDetail originalItem, SalesOrderDetail updatedItem)
{
using (AdventureWorksEntities context = new AdventureWorksEntities())
{
context.SalesOrderDetails.Attach(updatedItem);
// Check if the ID is 0, if it is the item is new.
// In this case we need to chage the state to Added.
if (updatedItem.SalesOrderDetailID == 0)
{
// Because the ID is generated by the database we do not need to
// set updatedItem.SalesOrderDetailID.
context.ObjectStateManager.ChangeObjectState(updatedItem, System.Data.EntityState.Added);
}
else
{
// If the SalesOrderDetailID is not 0, then the item is not new
// and needs to be updated. Because we already added the
// updated object to the context we need to apply the original values.
// If we attached originalItem to the context
// we would need to apply the current values:
// context.ApplyCurrentValues(“SalesOrderDetails”, updatedItem);
// Applying current or original values, changes the state
// of the attached object to Modified.
context.ApplyOriginalValues(“SalesOrderDetails”, originalItem);
}
context.SaveChanges();
}
}


Leave a Reply