一种选择是你说的做一个没有跟踪的查询。
ctx.Customers.MergeOption = MergeOption.NoTracking;
var customer = ctx.Customers.First(c => c.ID == 232);
然后客户可以修改'customer'
在内存要求,并没有在上下文中实际发生的情况。
现在,当你想真正让你可以做到这一点的变化:
// get the value from the database
var original = ctx.Customers.First(c => c.ID == customer.ID);
// copy values from the changed entity onto the original.
ctx.ApplyPropertyChanges(customer); .
ctx.SaveChanges();
现在,如果你是使用查询无论是性能或并发的原因不舒服,你可以添加一个新的扩展方法AttachAsModified(.. )到ObjectContext。
,看起来是这样的:
public static void AttachAsModified<T>(
this ObjectContext ctx,
string entitySet,
T entity)
{
ctx.AttachTo(entitySet, entity);
ObjectStateEntry entry =
ctx.ObjectStateManager.GetObjectStateEntry(entity);
// get all the property names
var propertyNames =
from s in entry.CurrentValues.DataRecordInfo.FieldMetadata
select s.FieldType.Name;
// mark every property as modified
foreach(var propertyName in propertyNames)
{
entry.SetModifiedProperty(propertyName);
}
}
现在你可以这样写代码:
ctx.Customers.MergeOption = MergeOption.NoTracking;
var customer = ctx.Customers.First();
// make changes to the customer in the form
ctx.AttachAsModified("Customers", customer);
ctx.SaveChanges();
现在你有没有并发或extranous查询。
现在唯一的问题是处理FK属性。你或许应该看看我的秘诀指数为帮助在这里:http://blogs.msdn.com/alexj/archive/2009/03/26/index-of-tips.aspx
希望这有助于
亚历
我目前正在与ApplyPropertyChanges方式实现,但附加一个修改实体看起来也很有趣。 Thx为输入! – 2009-05-07 00:12:52