0

Entity Frameworkを使用して更新するにはどうすればよいですか?更新された値でオブジェクトを渡していますが、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();

        }
    }
4

3 に答える 3

2

データベースからオブジェクトを再度フェッチせずにオブジェクトを更新する別の方法があるため、データベースへの移動のコストを節約できます。アタッチされるオブジェクトには、その主キーの値が必要です。

  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();    
        }
    }
于 2012-09-18T23:20:49.320 に答える
2

3 つのステップ:

  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...
    }
}
于 2012-09-18T21:11:13.940 に答える
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();
于 2012-09-18T21:13:52.113 に答える