一種選擇是你說的做一個沒有跟蹤的查詢。
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