About Me

Monday, November 28, 2011

Convert datatable into entity with BLToolkit

BLToolkit is a very good library that can make life easier when working with ADO.NET.
I used it for one project as a mapper that converts a data from a database into objects.

Normally, you have to pass a procedure name to the method of the BLToolkit library with params, specify what type you need to return and that's all.
However, few days ago, i needed more complicated thing.
Instead of making BLToolkit to do an SQL request, i did it by myself and get the DataTable.
It was needed to get some specific data from a DataTable that can't be converted into the existing type.
After that I expected that I can convert the result DataTable into list of Entities

Fortunately BLTollkit is able not only to make a conversion of  SQL requests on the fly, but has methods that allows to pass a DataTable into it, specify a desired type and get a result collection.

public IList<IScoutProfileInfo> SearchScouts(string toSearch, out int totalItems)
{
 totalItems = 0;
 using (DbManager db = new DbManager())
 {
  DataTable dataTable = db.SetSpCommand("usp_ScoutProfile_Search", toSearch).ExecuteDataTable();
  var enumerableRowCollection = dataTable.AsEnumerable();

  if (enumerableRowCollection.Any())
  {
   totalItems = (int) enumerableRowCollection.First()["TotalItems"];
  }

  MappingSchema schema = new MappingSchema();
  return schema.MapDataTableToList<ScoutProfileInfo>(dataTable).OfType<IScoutProfileInfo<().ToList();
 }
}

As you may see, the MappingSchema.MapDataTableToList does the trick.

1 comment:

  1. hi dear friend . you can use ExecuteList() method for get list of object from sql text command or storedprocedure

    ReplyDelete