ASP.NET MVC 2 – 使用UpdateModel和LINQ to Entities(.NET 3.5)时,“无法更新类型’XYZ’的模型”

我使用LINQ to Entities设置了一个模型,并且代码可以按预期添加到数据库中。 但是,当我使用.NET 3.5时,我无法使UpdateModel工作。

[HttpPost] public ActionResult Edit(Site.Models.XYZ xyz) { try { var original = db.XYZ.First(u => u.id == xyz.id); UpdateModel(original); db.SaveChanges(); return RedirectToAction("Index"); } catch (Exception ex) { return View("Error"); } } 

这导致以下exception:

 System.InvalidOperationException was caught Message=The model of type 'Site.Models.XYZ' could not be updated. Source=System.Web.Mvc StackTrace: at System.Web.Mvc.Controller.UpdateModel[TModel](TModel model, String prefix, String[] includeProperties, String[] excludeProperties, IValueProvider valueProvider) at System.Web.Mvc.Controller.UpdateModel[TModel](TModel model, String prefix) at Site.Controllers.XYZController.Edit(Site.Models.XYZ xyz) in D:***.cs:line 81 InnerException: 

如果我执行UpdateModel(xyz) ,则不会发生exception,但数据也不会保存。

如何让UpdateModel与它一起工作(不更新到.NET 4.0),为什么不能更新它(由于没有内部exception,exception没有用)?

管理解决问题。 可以通过以下两种方式之一完成:

 TryUpdateModel(original) 

要么

 db.ApplyPropertyChanges(original.EntityKey.EntitySetName, xyz) 

不知道为什么TryUpdateModel会起作用,但UpdateModel不会。 也许只是.NET 3.5中的一个错误。

我在MVC项目中所做的是从Codeplex获取DefaultModelBinder的源代码并将其粘贴到项目中的新类中,如MyDefaultModelBinder。 然后在global.asax中注册该模型绑定器:

 ModelBinders.Binders.DefaultBinder = new MyDefaultModelBinder(); 

这允许您在BindModel方法中设置断点,并且可以找出它无法绑定的原因。

使用TryUpdateModel()而不是UpdateModel()函数来解决此问题

UpdateModel()TryUpdateModel()函数都用于使用表单值更新模型并执行validation。

UpdateModel()TryUpdateModel()之间的区别

如果validation失败, UpdateModel()会抛出exception,因为TryUpdateModel()永远不会抛出exception,它会返回true或false

你可以这种方法(这对我有用)

protected internal void UpdateModel(TModel model, string[] includeProperties) where TModel : class;

例;

string[] includeProperty = { xyz.Id.ToString(),xyz.Name}; UpdateModel(uye, includeProperty);