65.9K
CodeProject is changing. Read more.
Home

Simple Model/Entity Mapper in C#

starIconstarIconstarIcon
emptyStarIcon
starIcon
emptyStarIcon

3.33/5 (2 votes)

Mar 12, 2015

CPOL
viewsIcon

18017

This is an alternative for "Simple Model/Entity Mapper in C#"

Introduction

The original article is http://www.codeproject.com/Tips/807820/Simple-Model-Entity-mapper-in-Csharp.

Original Article:

Quote:

Introduction

When working in C#, we may want to map one Model/Entity to another. Reflection is the key which can help us at this point.

So let’s see how to make a simple model or Entity mapper using reflections in C#.

Quote:

Background

Let’s say we have some models like:

IStudent interface

interface IStudent
{
    long Id { get; set; }
    string Name { get; set; }
}

Student class

class Student : IStudent
{
    public long Id { get; set; }
    public string Name { get; set; }
}

StudentLog class

class StudentLog : IStudent
{
    public long LogId { get; set; }
    public long Id { get; set; }
    public string Name { get; set; }
}

Where Student and StudentLog, both have some common properties (name and type is the same).

Some years ago, I wrote almost the same code, but we didn't have the 4.0 Framework. My code was really poor and ugly, so I made some changes before posting in this site.

I think my version is faster, since I use one less foreach.

Using the Code

public static TTarget MapTo<TSource, TTarget>(TSource aSource) where TTarget : new()
{
    const BindingFlags flags = BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic;

    TTarget aTarget = new TTarget();
    Hashtable sourceData = new Hashtable();
    foreach (PropertyInfo pi in aSource.GetType().GetProperties(flags))
    {                
        if (pi.CanRead)
        {
            sourceData.Add(pi.Name, pi.GetValue(aSource, null));
        }
    }

    foreach (PropertyInfo pi in aTarget.GetType().GetProperties(flags))
    {   
//fix from rvaquette           
        if (pi.CanWrite)
        {
            if(sourceData.ContainsKey(pi.Name))
            {
                pi.SetValue(aTarget, sourceData[pi.Name], null);
            }
        }
    }
    return aTarget;
}
Student source = new Student() { Id = 1, Name = "Smith" };
StudentLog target = MapTo<Student, StudentLog>(source);