Hi,
I am working on a Mvc4-project and I am wondering why I rather should use the method SaveObject() instead of myObject = myObject.Save() when inserting or updating the db?
The beginning of my code in my controller looks like the following:
public class HomeController : Csla.Web.Mvc.Controller, IModelCreator
{
public object CreateModel(Type modelType)
{
if (modelType.Equals(typeof(CustomerEdit)))
return CustomerEdit.NewCustomer();
else
return Activator.CreateInstance(modelType);
}
public ViewResult Index()
{
return View();
}
[
HttpPost]
public ViewResult Index(CustomerEdit model)
{
if (ModelState.IsValid)
{
SaveObject(model,
false);
.
.
.
.
and so on.
So again, my question in this example is why it is better to use
SaveObject(model, false); instead of simply doing as usual model = model.Save(); Thanks, Peter
Hi,
Have you tried to do look at the actual code i Save?
ViewModelBase.cs:
public virtual bool Save(ModelStateDictionary modelState, bool forceUpdate) { try { var savable = ModelObject as Csla.Core.ISavable; if (savable == null) throw new InvalidOperationException("Save"); ModelObject = (T)savable.Save(forceUpdate); return true; } catch (Csla.DataPortalException ex) { if (ex.BusinessException != null) modelState.AddModelError("", ex.BusinessException.Message); else modelState.AddModelError("", ex.Message); return false; } catch (Exception ex) { modelState.AddModelError("", ex.Message); return false; } }
MvcController.cs:
protected virtual bool SaveObject<T>(T item, Action<T> updateModel, bool forceUpdate) where T : class, Csla.Core.ISavable { try { ViewData.Model = item; if (updateModel != null) updateModel(item); ViewData.Model = item.Save(forceUpdate); return true; } catch (Csla.DataPortalException ex) { if (ex.BusinessException != null) ModelState.AddModelError("", ex.BusinessException.Message); else ModelState.AddModelError("", ex.Message); return false; } catch (Exception ex) { ModelState.AddModelError("", ex.Message); return false; } }
Basically - this method add some error handling to add errors to modelState and present the error message a little nicer. If it doesn't fit your needs then don't use it.
Hi Jonny,
Thanks for your reply. I just wanted to clarify and understand what the difference is since I realized that both methods work.
/Peter
Copyright (c) Marimer LLC