Mapping business Objects and Entity Object with reflection c#

11,689

You can use Automapper or Valueinjecter

Edit:

Ok I wrote a function that uses reflection, beware it is not gonna handle cases where mapped properties aren't exactly equal e.g IList won't map with List

public static void MapObjects(object source, object destination)
{
    Type sourcetype = source.GetType();
    Type destinationtype = destination.GetType();

    var sourceProperties = sourcetype.GetProperties();
    var destionationProperties = destinationtype.GetProperties();

    var commonproperties = from sp in sourceProperties
                           join dp in destionationProperties on new {sp.Name, sp.PropertyType} equals
                               new {dp.Name, dp.PropertyType}
                           select new {sp, dp};

    foreach (var match in commonproperties)
    {
        match.dp.SetValue(destination, match.sp.GetValue(source, null), null);                   
    }            
}
Share:
11,689
Hidsman
Author by

Hidsman

Updated on June 05, 2022

Comments

  • Hidsman
    Hidsman almost 2 years

    I want to somehow map entity object to business object using reflection in c# -

    public class Category
        {
            public int CategoryID { get; set; }
            public string CategoryName { get; set; }
        }
    

    My Entity Class has same properties, CategoryId and CategoryName.Any best practice using reflection or dynamic would be appreciated.

  • Hidsman
    Hidsman about 13 years
    i dont want to use any third party or open source
  • Hidsman
    Hidsman about 13 years
    string destinationPropertyName = LookupMapping(sourceType.ToString(),destinationType.ToString‌​(),sourceProperty.Na‌​me ) ; Here LookupMapping is Microsoft Dynamic CRM Function. how i can do it without CRM
  • Hidsman
    Hidsman about 13 years
    i need to use reflection to avoid fix number of properties.
  • Serguzest
    Serguzest about 13 years
    I wonder what makes you think it doesn't use reflection? GetValue, SetValue those are reflection methods.
  • Omu
    Omu about 13 years
    @Aaabb Bbaa with Valueinjecter you would do a.InjectFrom(b) and that's it
  • Michael
    Michael about 12 years
    I recently started working on a new project and found a copied version of this code in it. I would strongly recommend using AutoMapper or ValueInjecter as @Serguzest initially suggested as this piece of code created problems in our applications. For example, a List<string> would be null in the destination.
  • GiveEmTheBoot
    GiveEmTheBoot almost 10 years
    Tried your solution (in VB.NET but it's the same). I've added "If match.dp.CanWrite Then" in the foreach cycle. Destination property could not have a setter. I also changed the method signature in this way to make the method more typed: "Public Shared Sub MapObjects(Of T, S)(source As T, destination As S)". Hope it helps.