Mapping business Objects and Entity Object with reflection c#

前端 未结 3 1913
一生所求
一生所求 2020-12-20 02:03

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

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


        
3条回答
  •  天涯浪人
    2020-12-20 02:13

    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);                   
        }            
    }
    

提交回复
热议问题