加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

entity-framework – 如何使用EF更新控制器中的对象?

发布时间:2020-12-16 09:59:44 所属栏目:asp.Net 来源:网络整理
导读:我在谷歌搜索,但它似乎太明显,没有人在谈论这个. 我有一个我的表的存储库,我希望能够更新我的数据库. 在Linq2Sql上你有类似的东西: public void SaveCar(Car car){ if (carTable.GetOriginalEntityState(car) == null) { carTable.Attach(product); carTabl
我在谷歌搜索,但它似乎太明显,没有人在谈论这个.

我有一个我的表的存储库,我希望能够更新我的数据库.

在Linq2Sql上你有类似的东西:

public void SaveCar(Car car)
{
    if (carTable.GetOriginalEntityState(car) == null)
    {
        carTable.Attach(product);
        carTable.Context.Refresh(RefreshMode.KeepCurrentValues,car);
    }
    carTable.ContextSubmitChanges();
}

在控制器中,只需在POST Edit方法上调用此方法即可.

我如何在EF中做这样的事情?更好的方法.

我看到使用TryUpdateModel(模型)的代码,但我不确定是否更新我在数据库上的内容,或者我必须首先选择对象并使用FormCollection更新它…

我很困惑,我只需要从表单中获取一辆汽车并使用相同的ID从数据库更新汽车.那么,我需要在控制器和存储库中做些什么呢?

谢谢.

编辑:如果我不清楚,我真的不知道我放在那里是否需要转换为EF.我只是想知道如何使用EF更新对象的实例(EFCodeFirst是我正在使用的).我如何从表单接收实例并在数据库中更新它.

解决方法

TryUpdateModel方法可用于为对象分配值,使用其属性名称与Web请求中指定的值之间的映射.话虽这么说,你可以通过做这样的事情来实现相同的行为:

[HttpPost]
public ActionResult Edit(int id,FormCollection form)
{
    Car entity = new Car { Id = id };

    // This will attach the car entity to the content in the unchanged state.
    this.EntityFrameworkObjectContext.Cars.Attach(car);

    TryUpdateModel(entity,form.ValueProvider.ToXYZ()); // Can't remember the exact method signature right now

    this.EntityFrameworkObjectContext.SaveChanges();
    ...
}

将实体附加到上下文时,您基本上只是通知上下文您有一个实体,他应该注意这个实体.一旦附加了实体,上下文将跟踪对其所做的更改.

但是此方法仅适用于标量属性,因为不使用此方法更新导航属性.如果启用了外键属性(如分配给类别的产品也具有链接两者的CategoryId属性),您仍应该能够使用此方法(因为导航属性使用标量属性进行映射).

编辑:另一种方法是接受Car实例作为参数:

[HttpPost]
public ActionResult Edit(int id,Car car)
{
    Car entity = new Car { Id = id };

    // This will attach the car entity to the content in the unchanged state.
    this.EntityFrameworkObjectContext.Cars.Attach(entity);

    // It is important that the Car instance provided in the car parameter has the
    // the correct ID set. Since the ApplyCurrentValues will look for any Car in the
    // context that has the specified primary key of the entity supplied to the ApplyCurrentValues
    // method and apply it's values to those entity instance with the same ID (this
    // includes the previously attached entity).
    this.EntityFrameworkObjectContext.Cars.ApplyCurrentValues(car); 
    this.EntityFrameworkObjectContext.SaveChanges();
    ...
}

您还可以滚动自己的ModelBinder,它实际上具有对您的Entity Framework Context的引用,并查看是否在表单/查询中指定了Car.Id.如果存在ID,您可以直接从上下文中获取要更新的实体.此方法需要一些努力,因为您必须首先确保搜索ID,然后应用所有指定的属性值.如果你有兴趣,我可以给你一些考试.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读