Click here to Skip to main content
15,889,096 members
Articles / Programming Languages / C#
Alternative
Tip/Trick

Simple Model/Entity Mapper in C#

Rate me:
Please Sign up or sign in to vote.
3.33/5 (2 votes)
12 Mar 2015CPOL 17.4K   8   7
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

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

Student class

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

StudentLog class

C#
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

C#
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;
}
C#
Student source = new Student() { Id = 1, Name = "Smith" };
StudentLog target = MapTo<Student, StudentLog>(source);

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
Brazil Brazil
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
SuggestionIn your code, shoudn't it be "if (pi.CanWrite)" rather than "if (pi.CanRead)" in the second loop? Pin
rvaquette12-Mar-15 12:21
rvaquette12-Mar-15 12:21 
C#
foreach (PropertyInfo pi in aTarget.GetType().GetProperties(flags))
    {
        if (pi.CanWrite)
        {
            if(sourceData.ContainsKey(pi.Name))
            {
                pi.SetValue(aTarget, sourceData[pi.Name], null);
            }
        }
    }

GeneralRe: In your code, shoudn't it be "if (pi.CanWrite)" rather than "if (pi.CanRead)" in the second loop? Pin
ThiagoTane13-Mar-15 6:59
ThiagoTane13-Mar-15 6:59 
Generalcongratulation Pin
DiponRoy12-Mar-15 10:38
DiponRoy12-Mar-15 10:38 
GeneralRe: congratulation Pin
ThiagoTane13-Mar-15 7:03
ThiagoTane13-Mar-15 7:03 
Questionyou did not show how to use it Pin
Tridip Bhattacharjee12-Mar-15 7:52
professionalTridip Bhattacharjee12-Mar-15 7:52 
AnswerRe: you did not show how to use it Pin
ThiagoTane12-Mar-15 8:06
ThiagoTane12-Mar-15 8:06 
GeneralRe: you did not show how to use it Pin
Tridip Bhattacharjee12-Mar-15 21:28
professionalTridip Bhattacharjee12-Mar-15 21:28 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.