Noah Blumenthal's Blog

July 10, 2009

Model Binder that retrieves from DB

Filed under: Uncategorized — noahblu @ 2:20 am

Many times I need a model binder that will retrieve my model from a repository so that I can perform updates.  Here’s what I came up with.

   1: public class EntityRetrievalBinder<T, TRepository> : IModelBinder

   2:     where TRepository : IRepository<T>

   3: {

   4:     #region IModelBinder Members


   6:     public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)

   7:     {

   8:         var name = bindingContext.ModelName + ".ID";

   9:         ValueProviderResult idResult;

  10:         try

  11:         {

  12:             if (bindingContext.ValueProvider.TryGetValue(name, out idResult))

  13:             {

  14:                 Guid id = new Guid(idResult.AttemptedValue);

  15:                 var repository = StructureMap.ObjectFactory.GetInstance<TRepository>();

  16:                 T obj = repository.FindById(id);

  17:                 if (obj == null)

  18:                     throw new ArgumentException("Object not found");

  19:                 return obj;

  20:             }

  21:         }

  22:         catch (Exception e)

  23:         {

  24:         }

  25:         return null;

  26:     }

I changed a couple things for this post, but basically the logic is simple.  What this does is just retrieve the repository from StructureMap and then try to run the Find() method which takes a Guid ID as its only parameter.  Either this will return a null (if no ID was posted) or an object of type T OR it might throw an exception if the user posted an ID but that ID was not found.  I’ll show you in the next post how I tie everything together.


Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

Blog at

%d bloggers like this: