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

本文介绍了一种在Entity Framework (EF)中更新Detached对象的方法。通过定义ObjectStateEntry和EntityKey,使用TryGetObjectByKey获取原始对象,并调用ApplyPropertyChanges应用更改。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

今天发现几个同事都不知道在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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值