Automatic saving when updating records with SharpArchitecture

Another gotcha for newbie MVC/Sharp programmers (I include myself this time!). As mentioned in a previous post, with SharpArchitecture you need to decorate the method with the [Transaction] attribute in order to save the record you are creating. So far so good. What we hadn’t realised is that you don’t actually need to call the Repository’s SaveOrUpdate() method in order to update an existing record!

If you have a method such as the following in your controller (I am assuming you have created the relevant entity and repository), then this is actually enough to update your ‘RecordType’ database record! Presumably this happens because the transaction is committed once the method is returned. You still need to called SaveOrUpdate() to create new records.

I personally don’t like this feature (I don’t know if it is Sharp or nHibernate) because it is too easy to accidentally update something that shouldn’t be, but once you know it exists then you can look out for it.

[AcceptVerbs(HttpVerbs.Post)]
[Transaction]
public ActionResult Update(MyViewModel model)
{
     RecordType record = _myRepository.GetById(model.Id);
     if (record != null)
     {
           record.Description = model.Description;
      }
}
Advertisements

MVC: storing URL parameter value in ViewModel

Bit of a gotcha for newbie MVC programmers. If a name of a route parameter on your page is the same as a name of a property on your ViewModel then the value of the route parameter will be copied to your ViewModel property. This can actually be very useful, but causes an awful lot of head-scratching to start with if you were unaware of it!

For example, take the following route in your registry:

routes.MapRoute(
                "MyRoute",
                "ShowMe/{qid}",
                new { controller = "Show", action = "Me" }
                );

and then the View returned by the ‘Me’ controller method uses the following ViewModel:

public class ShowMeViewModel
{
      public string qid {get;set;}
}

Then when the page is called with the URL of ShowMe/TheWorld the ‘qid’ property of the ViewModel will become automatically set to ‘TheWorld’, regardless of what you try to set it to within the ‘Me’ controller method.