简体   繁体   English

如何通过传入对象使用实体框架进行更新

[英]How to update using Entity Framwork by passing in object

How do I update using Entity Framework? 如何使用实体框架进行更新? I'm passing in the object with the updated values, but I don't see an Update method. 我正在传递具有更新值的对象,但没有看到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();

        }
    }

Three steps: 三个步骤:

  1. Get the item to update from the context 从上下文中获取要更新的项目
  2. Copy over the updated properties from the entity you pass your update method 从您通过更新方法的实体中复制更新后的属性
  3. Save the changes. 保存更改。

Roughly: 大致:

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...
    }
}

There is another way of updating object without re-fetching it from the database again thus by saving cost of a trip to database. 还有另一种更新对象的方法,而无需再次从数据库重新获取它,从而节省了访问数据库的费用。 The object being attached must have a value for its primary key. 附加的对象必须为其主键具有一个值。

  1. Attach the updated object to the context 将更新的对象附加到上下文
  2. Change it's state to 'modified'. 将其状态更改为“已修改”。
  3. Call SaveChanges() method of the context 调用上下文的SaveChanges()方法

Like: 喜欢:

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

If you're updating the record then you'd do something like this: 如果您要更新记录,则可以执行以下操作:

//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 you want to update/add things at the same time then you'd do: 如果您想同时更新/添加内容,则可以执行以下操作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM