`
ribishuangba
  • 浏览: 285445 次
文章分类
社区版块
存档分类
最新评论

Entity Framework - 更新detached对象的正确方法

 
阅读更多

今天发现几个同事都不知道在EF中更新detached对象的正确(or 官方)方法:

private
 static
 void
 ApplyItemUpdates(SalesOrderDetail updatedItem)
{
// Define an ObjectStateEntry and EntityKey for the current object.
EntityKey key;
object originalItem;

using (AdventureWorksEntities advWorksContext =
new AdventureWorksEntities())
{
try
{
// Create the detached object's entity key.
key = advWorksContext.CreateEntityKey("SalesOrderDetail" , updatedItem);

// Get the original item based on the entity key from the context
// or from the database.
if (advWorksContext.TryGetObjectByKey(key, out originalItem))
{
// Call the ApplyPropertyChanges method to apply changes
// from the updated item to the original version.
advWorksContext.ApplyPropertyChanges (
key.EntitySetName, updatedItem);
}

advWorksContext.SaveChanges();
}
catch (InvalidOperationException ex)
{
Console.WriteLine(ex.ToString());
}
}
}

http://msdn.microsoft.com/en-us/library/bb896248.aspx

关于detached对象以及Attach的解释:

http://msdn.microsoft.com/en-us/library/bb896271.aspx
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics