Cleanest Way To Map Entity To DTO With Linq Select?

前端 未结 4 1979
梦如初夏
梦如初夏 2020-12-13 19:45

I\'ve been trying to come up with a clean and reusable way to map entities to their DTOs. Here is an example of what I\'ve come up with and where I\'m stuck.

4条回答
  •  臣服心动
    2020-12-13 20:39

    Automapper is the best way .

    For me, I use this for simple objects only, but I don't recommend it

      public static class ObjectMapper
    {
        public static T Map(object objfrom, T objto)
        {
            var ToProperties = objto.GetType().GetProperties();
            var FromProperties = objfrom.GetType().GetProperties();
    
            ToProperties.ToList().ForEach(o =>
                {
                    var fromp = FromProperties.FirstOrDefault(x => x.Name == o.Name && x.PropertyType == o.PropertyType);
                    if (fromp != null)
                    {
                        o.SetValue(objto, fromp.GetValue(objfrom));
                    }
                });
    
            return objto;
        }
    }
    

    And I call it like that wherever I want

       var myDTO= ObjectMapper.Map(MyObject, new MyObjectDTO());
    

提交回复
热议问题