2012-09-18 73 views
0

如何使用實體框架進行更新?我傳入具有更新值的對象,但沒有看到Update方法。如何通過傳遞對象使用實體框架更新

public void UpdateRecipient(Domain.Entities.RecipientEntity recipient) 
    { 
     using (EfDbContext context = CreateEfDbContext(recipient.ApplicationId.ToString())) 
     { 

      context.Recipients. //?? I don't see an update method 
      context.SaveChanges(); 

     } 
    } 

回答

2

三個步驟:

  1. 獲得該項目從上下文更新
  2. 複製了從實體更新的屬性你通過更新方法
  3. 保存更改。

大致爲:

using (EfDbContext context = CreateEfDbContext(recipient.ApplicationId.ToString())) 
{ 
    var toUpdate = context.Recipients.SingleOrDefault(r => r.Id == recipient.Id); 
    if (toUpdate != null) 
    { 
     toUpdate.Field1 = recipient.Field1; 
     // Map over any other field data here. 

     context.SaveChanges(); 
    } 
    else 
    { 
     // Handle this case however you see fit. Log an error, throw an error, etc... 
    } 
} 
1

如果要更新的記錄,那麼你會做這樣的事情:

//Retrieve the entity to be updated 
Entity row = context.Recipients.Single(a => a.Id == recipient.Id); 

//Update a column 
row.Name = recipient.Name; 

//Save changes 
context.SaveChanges(); 

如果你想更新/在同一時間添加的東西那麼你會這樣做:

if(!context.Recipients.Any(a => Id == recipient.Id)) 
{ 
    context.Recipients.Add(recipient); 
} 
else 
{ 
    Entity row = context.Recipients.Single(a => a.Id == recipient.Id); 

    row.Name = recipient.Name; 
} 

context.SaveChanges(); 
2

還有另一種方法來更新對象witho再次從數據庫中重新獲取它,從而節省到數據庫的旅程成本。被連接的對象必須具有主鍵的值。

  1. 安裝更新的對象上下文
  2. 改變它的狀態設置爲「修改」。
  3. 呼叫上下文的SaveChanges()方法

像:

public void UpdateRecipient(Domain.Entities.RecipientEntity recipient) 
    { 
     using (EfDbContext context = CreateEfDbContext(recipient.ApplicationId.ToString())) 
     { 
      context.Attach(recipient); 
      context.ObjectStateManager.ChangeObjectState(recipient,EntityState.Modified); 
      context.SaveChanges();  
     } 
    }