我有一些来自其他层的数据,它代表一个EF对象.当它是新的时,我这样做:
context.AddToCustomer(mynewobject);
context.SaveChanges();
Run Code Online (Sandbox Code Playgroud)
但现在我的数据形成了一个现有的对象,所以我希望上下文知道我想要更新数据而不是插入数据.
我见过'ApplyPropertyChanges',但我无法弄清楚如何使用它.我也见过人们这样做:
Customer existingOne = (from n in context.Customers
where n.id = mynewobject.id select n).First()
existingOne.name = mynewobject.name
existingOne.address= mynewobject.address
context.SaveChanges();
Run Code Online (Sandbox Code Playgroud)
但这似乎有点奇怪,因为我必须手动设置所有道具并首先读取整个对象.
在实体框架5中,您将了解以下内容:
/// <summary>
/// Updates an entity
/// </summary>
/// <param name="input">A entity</param>
/// <returns>The updated object</returns>
public TEntity Update(TEntity input)
{
using (var context = GetContext())
{
context.Set<TEntity>().Attach(input);
var entry = context.ChangeTracker.Entries<TEntity>().FirstOrDefault(e => e.Entity == input);
if (entry != null)
entry.State = EntityState.Modified;
context.SaveChanges();
}
return input;
}
Run Code Online (Sandbox Code Playgroud)
虽然我怀疑是否值得“优化”更新,但您仍然可以按照您的要求进行。这在 EF 4 中更容易,但在 EF 1 中也可以实现。另请参阅这篇文章。
public static void AttachAsModified<T>(this ObjectSet<T> objectSet, T entity) where T : class
{
objectSet.Attach(entity);
objectSet.Context.ObjectStateManager.ChangeObjectState(entity, EntityState.Modified);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6216 次 |
| 最近记录: |