Tuesday, June 24, 2014

AutoMapperesque mappings from DataSet stuff to better C# objects in DotNetNuke.

I'm understanding a little more how the IHydratable objects are hydrated in a DotNetNuke application. It is pretty cool and effectively creates a way to hydrate objects out of a database by stored procedures in an ORMish, loosely-coupled manner keeping core object classes independent from the data layer which feeds their object instances. Assuming you have a class, in this example, FluffyBunny, which inherits from IHydratable in the DotNetNuke.Entities.Modules namespace, you could call a stored procedure and get a list of fluffy bunnies like so:

List<FluffyBunny> foo = GetStuff<FluffyBunny>("GetFluffyBunnyByColor", new []
   {
      new SqlParameter(Color, "White")
   });

 
 

"GetStuff" starts out like this...

public List<T> GetStuff<T>(string sprocName, params SqlParameter[] variables)
{
   using (SqlConnection go = new SqlConnection(_connectionString))
   {
      connection.Open();
      using (SqlCommand act = new SqlCommand(sprocName, go)
         { CommandType = CommandType.StoredProcedure
      })
      {

 
 

Next would come some usual logic for associating the SqlParameter stuff with the SqlCommand. Finally, "GetStuff" could be wrapped up like so:

         using (SqlDataReader read = act.ExecuteReader())
         {
            return CBO.FillCollection<T>(read);
         }

 
 

.FillObject<T> could be used instead of .FillCollection<T> if you were just hydrating a single object. Both of these tricks are from the DotNetNuke.Common.Utilities namespace. This stuff seems pretty neat. FluffyBunny has to have getsetters which correspond to the column names in the database one-to-one to pull this off of course. I suppose you could fudge some name changes with AS in the stored procedure itself. I don't recommend using DotNetNuke for a CMS, but it might be OK to selectively use this piece of its functionality. The GetStuff method also shows off some of the cool ways C# generics may be manipulated as discussed in C# 4.0 in a Nutshell. I supposed this hydration posting is multiheaded... not unlike.. the Hydra!

No comments:

Post a Comment