Click here to Skip to main content
Click here to Skip to main content

Simple Model/Entity Mapper in C#

, 2 Sep 2014 CPOL
Rate this:
Please Sign up or sign in to vote.
Let’s see how to make a simple model or Entity mapper using reflections in C#

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

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).

MapperUtility

Here is the utility class which we are going to use for mapping:

TTarget MapTo<TSource, TTarget> (this TSource aSource, TTarget aTarget) - maps properties of aSource to given aTarget, and returns the aTarget

TTarget CreateMapped<TSource, TTarget> (this TSource aSource) - maps properties of aSource to a newly created object of type TTarget and returns it.

Mapping would work for the properties where, name and type are same for TSource and TTarget.

public static class MapperUtility
{
    /*passing values to given object*/
    public static TTarget MapTo<TSource, TTarget>(this TSource aSource, TTarget aTarget)
    {
        const BindingFlags flags = BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic;
       
        /*TODO: find fields*/
        var srcFields = (from PropertyInfo aProp in typeof(TSource).GetProperties(flags)
                           where aProp.CanRead     //check if prop is readable
                             select new
                             {
                                 Name = aProp.Name,
                                 Type = Nullable.GetUnderlyingType(aProp.PropertyType) ?? aProp.PropertyType
                             }).ToList();
        var trgFields = (from PropertyInfo aProp in aTarget.GetType().GetProperties(flags)
                             where aProp.CanWrite   //check if prop is writeable
                                 select new
                                 {
                                     Name = aProp.Name,
                                     Type = Nullable.GetUnderlyingType(aProp.PropertyType) ?? aProp.PropertyType
                                 }).ToList();

        /*TODO: common fields where name and type same*/
        var commonFields = srcFields.Intersect(trgFields).ToList();

        /*assign values*/
        foreach (var aField in commonFields)
        {
            var value = aSource.GetType().GetProperty(aField.Name).GetValue(aSource, null);
            PropertyInfo propertyInfos = aTarget.GetType().GetProperty(aField.Name);
            propertyInfos.SetValue(aTarget, value, null);
        }
        return aTarget;
    }

    /*returns new object with mapping*/
    public static TTarget CreateMapped<TSource, TTarget>(this TSource aSource) where TTarget : new()
    {
        return aSource.MapTo(new TTarget());
    }
}

Create New Mapped

Would create new mapped object of StudentLog from object source of type Student:

Student source = new Student() { Id = 1, Name = "Smith" };
/*get new object, which been mapped*/
StudentLog newMapped = source.CreateMapped<Student, StudentLog>();

Map to Existing One

Would map from target of type Student to an existing aSourceLog of type StudentLog:

/*mapp to existing object*/
StudentLog aSourceLog = new StudentLog();
Student target = new Student();
target.Id = 2;
target.Name = "Tom";

aSourceLog = target.MapTo(aSourceLog);
//or
target.MapTo(aSourceLog);

Limitations

  1. I have used framework 4.
  2. This mapper only works for classes. If you try with struct, it wouldn’t be able to map, or if you try to use List<Student>, it would throw an error.
  3. I only needed that much so I created it, if you need to do some more things, check AutoMapper.

Find solution of VS2010 in the attachment.

License

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

Share

About the Author

DiponRoy

Bangladesh Bangladesh
No Biography provided

Comments and Discussions

 
GeneralMy vote of 5 PinprofessionalVolynsky Alex7-Sep-14 11:52 
GeneralRe: My vote of 5 Pinmemberdiponsust8-Sep-14 2:40 
GeneralRe: My vote of 5 PinprofessionalVolynsky Alex8-Sep-14 10:28 
SuggestionGood idea... Look at this PinmemberJorge Varas3-Sep-14 10:59 
GeneralRe: Good idea... Look at this Pinmemberdiponsust3-Sep-14 23:08 
GeneralMy vote of 5 PinmemberHumayun Kabir Mamun2-Sep-14 19:20 
GeneralRe: My vote of 5 Pinmemberdiponsust23-Sep-14 9:07 
BugPlease check the code Pinmvp Akhil Mittal 2-Sep-14 18:54 
GeneralRe: Please check the code Pinmemberdiponsust2-Sep-14 21:00 
GeneralRe: Please check the code Pinmvp Akhil Mittal 2-Sep-14 22:16 
GeneralRe: Please check the code Pinmemberdiponsust23-Sep-14 9:06 

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

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

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.141223.1 | Last Updated 2 Sep 2014
Article Copyright 2014 by DiponRoy
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid