2012-07-05 3 views
0

값을 한 형식에서 다른 형식으로 매핑해야했습니다. 두 개체는 이미 인스턴스화되었고 값을가집니다. 하나는 MVC ViewModel 객체이고 다른 하나는 Hibernate Entity이다. 엔티티에 뷰 모델을 매핑하고 싶지만 값이 다른 경우에만 값을 할당해야합니다. 나는 또한 변경 사항을 기록하고 싶었다. 나는 깔끔하게 매핑 방법/함수로 감싸고 싶다. 나는 이것이 AutoMapper로 가능하다고 생각하지 않는다. 그렇지? 나는 또한 커스텀 매핑 함수를 생각해 냈지만, 더 좋은 방법이 있는가?사용자 지정 속성 매핑 - 변경시 기존 개체

답변

0

은 내가 더 나은 대상 객체 :

/// <summary> 
/// Maps a property value from one object type to another. 
/// Assignment only if values are different. 
/// Change is recorded to stringbuilder object with changeName name 
/// </summary> 
/// <typeparam name="TDestination">Type of destination object</typeparam> 
/// <typeparam name="TSourceValue">Type of source object</typeparam> 
/// <param name="changeName">what to call the change for logging</param> 
/// <param name="dObj">the desitnation object instance on which to call the extension method</param> 
/// <param name="destProp">destination (old value) property</param> 
/// <param name="sVal">the source (new) value</param> 
/// <param name="sbChanges">where to log the changes</param> 
/// <returns>1 if values were different, 0 if values were the the same</returns> 
/// <example> 
///  var sbChanges = new StringBuilder(); 
///  var c = 0; 
///  c += DestObj.MapChange("My Property", x => x.DestProp, SourceObj.SourceProp, sbChanges); 
/// </example> 
public static short MapChange<TDestination, TSourceValue>(this TDestination dObj, string changeName, Expression<Func<TDestination, object>> destProp, 
                 TSourceValue sVal, StringBuilder sbChanges) 
{ 
    var dExpr = destProp.Body as MemberExpression ?? ((UnaryExpression)destProp.Body).Operand as MemberExpression; 

    if (dExpr == null) 
     throw new Exception("Destination expression must be a field or property"); 

    var dProp = typeof(TDestination).GetProperty(dExpr.Member.Name); 

    var dVal = dProp.GetValue(dObj, null); 

    //Equals(null, null) is false so also compare by reference 
    if (!ReferenceEquals(dVal, sVal) && !Equals(dVal, sVal)) 
    { 
     dProp.SetValue(dObj, sVal, null); 

     if (sVal == null) // http://stackoverflow.com/questions/5340817/what-should-i-do-about-possible-compare-of-value-type-with-null 
      sbChanges.AppendFormat("Removed '{0}'\r", changeName); 
     else if (dVal == null || sVal is bool) 
      sbChanges.AppendFormat("Set '{0}' to '{1}'\r", changeName, sVal); 
     else //other types 
      sbChanges.AppendFormat("Set '{0}' from '{1}' to '{2}'\r", changeName, dVal, sVal); 

     return 1; 
    } 

    return 0; 
} 
에 확장으로 그것을 좋아하지 생각