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();

        }
    }
4

3 回答 3

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...
    }
}
于 2012-09-18T21:11:13.940 回答
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 回答
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 回答