Skip to main content

Convert your datatable into generic poco object in c# using linq, ado and reflections.



The most common problem that we face these days is to create a common class and method that can be used across all the projects and codes.

So today I will be sharing my code where you can see how to make and create a generic function without using entity framework for ado. net.

The scenario is like you have an old software that uses stored procedure to return set of entities as a data-table, you do not want to re-write the back-end code as you are creating a web API in c# which needs to be delivered asap.

You need to map these data tables to models as you might be using MV* pattern.

So here we will be doing one to one mapping of model to data- table, and in similar fashion insert or update can also be done.

So basically we are converting a data-table to list of strongly typed object model to do CRUD operations.

So we have following things before hand.

A helper class is referenced as the database(dbFactory) which executes ado. net commands and returns data whether it's a nonquery or a dataset/data tables.

Below is the code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
        /// <summary>
        /// Call the Get to fetch Data
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <typeparam name="U"></typeparam>
        /// <param name="model"></param>
        /// <param name="param"></param>
        /// <param name="procName"></param>
        /// <returns></returns>
        public static List<T> Get<T, U>(T model, U param, string procName) where T : new()
        {
            Type type = param.GetType();
            Type modelType = param.GetType();
            var propertiesParam = typeof(U).GetProperties();
            prm = new SqlParameter[propertiesParam.Length];

            for (int i = 0; i < propertiesParam.Length; i++)
            {
                prm[i] = new SqlParameter(propertiesParam[i].Name.ToString(), propertiesParam[i].GetValue(param));
            }
            database = new DbFactory();
            return ToList(new T(), database.returnDataTable(strConn, procName, prm, 1));
        }
        
        
        /// <summary>
        /// Convert DataTable to Strongly typed objects
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="Model"></param>
        /// <param name="dataTable"></param>
        /// <returns></returns>
        private static List<T> ToList<T>(T Model, DataTable dataTable) where T : new()
        {
            var dataList = new List<T>();
            const BindingFlags flags = BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic;
            var objFieldNames = (from PropertyInfo aProp in typeof(T).GetProperties(flags)
                                 select new
                                 {
                                     Name = aProp.Name,
                                     Type = Nullable.GetUnderlyingType(aProp.PropertyType) ?? aProp.PropertyType
                                 }).ToList();

            var dataTblFieldNames = (from DataColumn aHeader in dataTable.Columns
                                     select new
                                     {
                                         Name = aHeader.ColumnName,
                                         Type = aHeader.DataType
                                     }).ToList();

            var commonFields = objFieldNames.Intersect(dataTblFieldNames).ToList();

            foreach (DataRow dataRow in dataTable.AsEnumerable().ToList())
            {
                var aTSource = new T();
                foreach (var aField in commonFields)
                {
                    PropertyInfo propertyInfos = aTSource.GetType().GetProperty(aField.Name);
                    var value = (dataRow[aField.Name] == DBNull.Value) ? null : dataRow[aField.Name]; //if database field is nullable
                    propertyInfos.SetValue(aTSource, value, null);
                }
                dataList.Add(aTSource);
            }
            return dataList;

        }

So in the above code as you can see these are generics methods in which we need to pass a model, sql proc name and parameters, we will recieve the model with values in it. The catch is the model properties name should be same as table column headers, my next target will be to have attributes functionality over model properties so we can have custom names of entity like in MVC.

Anyway ToList function above will convert your sql datatable to model entity using reflections capabilities of c#.

Well just copy paste the above code and enjoy.

Comments

Popular posts from this blog

Run CSS specific to Internet Explorer - Browser Hack

Run CSS specific to Internet Explorer - Browser Hack Referencing to the following blog post, we are going to make CSS targeting exclusively to IE browser, to make it work first we should know what are media queries. A media query consists of a media type and at least one expression that limits the style sheets' scope by using media features, such as width, height, and color. Media queries, added in CSS3, let the presentation of content be tailored to a specific range of output devices without having to change the content itself. For Ex: < style > @media (max-width : 600px) { .facet_sidebar { display : none ; } } So below we will wrap the IE specific CSS rules in @media blocks and trick IE into rendering @media blocks that use media queries. Targeting only IE browsers Style rules defined in the following blocks will only be applied in IE, other browsers will ignore them. IE 6 and 7  @media screen\9 {     body { background: red; ...

Send a Fax in windows using faxcomexlib and TAPI in VB code .Net

An application that provides sending fax from faxmodem, connected to the computer, will be explained in the following post.  We can use Telephony Application Programming Interface (TAPI) and the Fax Service Extended Component Object Model (COM) API to send fax. The fax service is a Telephony Application Programming Interface (TAPI)-compliant system service that allows users on a network to send and receive faxes from their desktop applications. The service is available on computers that are running Windows 2000 and later. The fax service provides the following features: Transmitting faxes Receiving faxes Flexible routing of inbound faxes Outbound routing Outgoing fax priorities Archiving sent and received faxes Server and device configuration management Client use of server devices for sending and receiving faxes Event logging Activity logging Delivery receipts Security permissions The following Microsoft Visual Basic code example sends a fax. Note that...