Sai A Sai A
Updated date Aug 04, 2023
In this blog, we will learn how to efficiently convert objects to DataRows in C# using two different methods - reflection and AutoMapper.
  • 2.1k
  • 0
  • 0

Introduction:

In C#, developers often encounter situations where they need to convert objects into DataRows to facilitate data processing and manipulation. DataRows are essential components of DataTables, commonly used to store and manage tabular data. This blog explores two efficient techniques for converting objects to DataRows in C# while maintaining code readability and performance.

Method 1: Using Reflection

Reflection is a powerful feature in C# that allows us to inspect and manipulate types, properties, and methods at runtime. By leveraging reflection, we can dynamically extract the properties of an object and map them to corresponding columns in a DataRow. Let's dive into a step-by-step code example to demonstrate this approach.

using System;
using System.Data;
using System.Reflection;

public class Student
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }
}

public class ObjectToDataRowConverter
{
    public static DataRow ConvertObjectToDataRow(object obj, DataTable dataTable)
    {
        DataRow dataRow = dataTable.NewRow();
        Type objectType = obj.GetType();

        foreach (PropertyInfo property in objectType.GetProperties())
        {
            if (dataTable.Columns.Contains(property.Name))
            {
                dataRow[property.Name] = property.GetValue(obj);
            }
        }

        return dataRow;
    }
}

class Program
{
    static void Main()
    {
        DataTable dataTable = new DataTable();
        dataTable.Columns.Add("Id", typeof(int));
        dataTable.Columns.Add("Name", typeof(string));
        dataTable.Columns.Add("Age", typeof(int));

        Student student = new Student { Id = 1, Name = "John Doe", Age = 20 };

        DataRow dataRow = ObjectToDataRowConverter.ConvertObjectToDataRow(student, dataTable);

        Console.WriteLine("DataRow:");
        foreach (DataColumn column in dataTable.Columns)
        {
            Console.WriteLine($"{column.ColumnName}: {dataRow[column]}");
        }
    }
}

Output:

DataRow:
Id: 1
Name: John Doe
Age: 20

Method 2: Using AutoMapper

While the reflection-based approach is flexible, it may become inefficient for larger datasets or complex object hierarchies. To address this, we can employ third-party libraries like AutoMapper, which automates the object-to-DataTable mapping process and improves performance significantly.

using System;
using System.Data;
using AutoMapper;

public class Student
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }
}

public class ObjectToDataTableMapper
{
    public static DataTable ConvertObjectToDataTable<T>(T obj)
    {
        var config = new MapperConfiguration(cfg =>
        {
            cfg.CreateMap<T, DataTable>().ConvertUsing<CustomConverter>();
        });
        var mapper = config.CreateMapper();

        return mapper.Map<T, DataTable>(obj);
    }
}

public class CustomConverter : ITypeConverter<Student, DataTable>
{
    public DataTable Convert(Student source, DataTable destination, ResolutionContext context)
    {
        destination.Rows.Add(source.Id, source.Name, source.Age);
        return destination;
    }
}

class Program
{
    static void Main()
    {
        Student student = new Student { Id = 1, Name = "John Doe", Age = 20 };

        DataTable dataTable = ObjectToDataTableMapper.ConvertObjectToDataTable(student);

        Console.WriteLine("DataTable:");
        foreach (DataRow dataRow in dataTable.Rows)
        {
            foreach (DataColumn column in dataTable.Columns)
            {
                Console.WriteLine($"{column.ColumnName}: {dataRow[column]}");
            }
        }
    }
}

Output:

DataTable:
Id: 1
Name: John Doe
Age: 20

Conclusion:

In this blog, we explored two efficient methods for converting objects to DataRows in C#. The first method utilized reflection, enabling dynamic property extraction and mapping. While versatile, it may lack performance for large datasets. The second method employed AutoMapper, a powerful mapping library that significantly improves conversion speed.

Comments (0)

There are no comments. Be the first to comment!!!