Preventing EF4 ConstraintException when invoking TryUpdateModel
Posted
by twk
on Stack Overflow
See other posts from Stack Overflow
or by twk
Published on 2010-05-14T21:09:19Z
Indexed on
2010/05/14
21:14 UTC
Read the original article
Hit count: 291
Given following ASP.NET MVC controller code:
[HttpPost] public ActionResult Create(FormCollection collection) { string[] whitelist = new []{ "CompanyName", "Address1", "Address2", ... }; Partner newPartner = new Partner(); if (TryUpdateModel(newPartner, whitelist, collection)) { var db = new mainEntities(); db.Partners.AddObject(newPartner); db.SaveChanges(); return RedirectToAction("Details/" + newPartner.ID); } else { return View(); } }
The problem is with the Entity Framework 4: the example Partner entity is mapped to a database table with it's fields NOT ALLOWED to be NULL (which is ok by design - they're required).
Unfortunately, invoking TryUpdateModel when some of the properties are nulls produces ConstraintException which is not expected! I do expect that TryUpdateModel return false in this case.
It is ok that EF wouldn't allow set a property value to null if it should not be, but the TryUpdateMethod should handle that, and add the error to ModelState errors collection.
I am wrong, or somebody screwed the implementation of TryUpdateModel method?
© Stack Overflow or respective owner