Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Simple Model/Entity Mapper in C#

0.00/5 (No votes)
12 Mar 2015 1  
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);

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here