gpt4 book ai didi

c# - 带有 Entity Framework 的强类型 ASP.NET MVC

转载 作者:行者123 更新时间:2023-11-30 19:00:51 24 4
gpt4 key购买 nike

此代码未能实际保存任何更改:

//
// POST: /SomeType/Edit/5

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(Guid id, SomeType Model)
{
db.AttachTo(Model.GetType().Name, Model);
db.ApplyPropertyChanges(Model.EntityKey.EntitySetName, Model);
db.SaveChanges();
return RedirectToAction("Index");
}

ASP.NET MVC 将对象模型创建为 Department 类型的 EntityObject,其 EntityState 值为 Detached

使用AttachTo方法后,其EntityState变为Unchanged

MSDN on Attaching Objects (Entity Framework)

Objects are attached to the object context in an Unchanged state.

由于其Unchanged 状态,ApplyPropertyChanges 方法什么都不做。

我希望它的状态为 Modified

MSDN on EntityState Enumeration

Detached
The object exists but it is not being tracked by Object Services. An entity is in this state immediately after it has been created and before it is added to the object context. An entity is also in this state after it has been removed from the context by calling the Detach method or if it is loaded using a NoTrackingMergeOption.

Unchanged
The object has not been modified since it was loaded into the context or since the last time that the SaveChanges method was called.

Modified
The object is changed but the SaveChanges method has not been called.

我无法将 EntityObject 的 EntityState 属性显式设置为 Modified。它是只读的。

EntityObjects 是不是不可能有强类型的 MVC Controller ?

最佳答案

您需要从 ObjectContext 中获取 ObjectStateManager。使用 ObjectStateManager,您可以显式设置对象的状态,而无需调用数据库:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(Guid id, SomeType Model)
{
db.AttachTo(Model.GetType().Name, Model);

ObjectStateManager stateMgr = db.ObjectStateManager;
ObjectStateEntry stateEntry = stateMgr.GetObjectStateEntry(model);
stateEntry.SetModified(); // Make sure the entity is marked as modified
//db.ApplyPropertyChanges(Model.EntityKey.EntitySetName, Model);

db.SaveChanges();
return RedirectToAction("Index");
}

ObjectStateEntry 还允许您通过 SetModifiedProperty 应用更细粒度的状态更改数据。如果您调用 SetModified,EF 会将整个实体视为已修改,并将每个属性持久保存到数据存储中。通过 SetModifiedProperty,EF 可以优化查询,只涉及实际发生变化的属性。使用 SetModifiedProperty 显然更复杂,因为您通常需要知道每个属性的原始值。

希望对您有所帮助。 ObjectStateManager 是 EF 工具箱中一个功能强大的小工具,可以帮助提高 EF v1.0 在其他方面表现不佳的性能和效率。

关于c# - 带有 Entity Framework 的强类型 ASP.NET MVC,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/899734/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com