Popular

Obten claves web y navega gratis Router keygen para Android

Error 403 Forbidden con phpmyadmin y WAMP Server

Realizar suma, resta y división con javascript

Copiar propiedades de un objeto a otro objeto (VB.NET)

Problema: 

Estoy intentando copiar las propiedades de un objeto "Auto" a un objeto "Vehiculo" el cuál tiene propiedades en común esto lo trato de realizar para evitar establecer propiedad a propiedad el mapeo correspondiente ya que los objetos son complejos de más de 50 campos y lo quiero hacer en varias ocasiones. 

La clases que se muestran aquí son de prueba: 
  
    
 Public Class Auto

        Private _Modelo As String
        Private _Nombre As String
        Private _NoCapacidad As Int32

        Public Property Modelo As String
            Get
                Return Me._Modelo
            End Get
            Set(value As String)
                Me._Modelo = value
            End Set
        End Property

        Public Property Nombre As String
            Get
                Return Me._Nombre
            End Get
            Set(value As String)
                Me._Nombre = value
            End Set
        End Property

        Public Property NoCapacidad As Integer
            Get
                Return Me._NoCapacidad
            End Get
            Set(value As Integer)
                Me._NoCapacidad = value
            End Set
        End Property
    End Class
    
    Public Class Vehiculo

        Private _Modelo As String
        Private _Nombre As String
        Private _Color As String

        Public Property Modelo As String
            Get
                Return Me._Modelo
            End Get
            Set(value As String)
                Me._Modelo = value
            End Set
        End Property

        Public Property Nombre As String
            Get
                Return Me._Nombre
            End Get
            Set(value As String)
                Me._Nombre = value
            End Set
        End Property

        Public Property Color As String
            Get
                Return Me._Color
            End Get
            Set(value As String)
                Me._Color = value
            End Set
        End Property
    End Class
    
   
 Solución: 
Por medio de Reflection vamos a realizar esto, crearemos una nueva clase "PropertyCopy" la cuál nos apoyará a realizar esto, para ello implementamos lo siguiente: 



  
    
 Public Class PropertyCopy(Of TParent As Class, TChild As Class)
    Public Shared Sub Copy(ByVal parent As TParent, ByVal child As TChild)
        Dim parentProperties = parent.[GetType]().GetProperties()
        Dim childProperties = child.[GetType]().GetProperties()

        For Each parentProperty In parentProperties

            For Each childProperty In childProperties

                If parentProperty.Name.ToUpper() = childProperty.Name.ToUpper() AndAlso parentProperty.PropertyType = childProperty.PropertyType Then

                    If ValidateGetValueValid(parentProperty, parent) Then
                        childProperty.SetValue(child, parentProperty.GetValue(parent, Nothing), Nothing)

                        'Verificar si existe la propiedad especified para los elementos ya que esta debe habilitarse de otra forma no se envíara el parametro. 
                        Dim myFieldSpecified As System.Reflection.PropertyInfo = childProperties _
                                                                        .SingleOrDefault(Function(x) x.Name = childProperty.Name + "Specified")
                        If myFieldSpecified IsNot Nothing Then
                            Dim genericType As System.Type = myFieldSpecified.PropertyType
                            If genericType Is GetType(Boolean) Then
                                myFieldSpecified.SetValue(child, True, Nothing)
                            End If
                        End If
                    End If

                    Exit For
                End If
            Next
        Next
    End Sub

    Private Shared Function ValidateGetValueValid(ByVal parentProperty As System.Reflection.PropertyInfo,
                                           ByVal parent As TParent) As Boolean

        If parentProperty.GetValue(parent, Nothing) Is Nothing Then
            Return False
        End If

        'En caso de ser una fecha y viene con la fecha minima del sistema no se establece.
        If parentProperty.GetValue(parent, Nothing).GetType() = System.Type.GetType("System.DateTime") Then
            If parentProperty.GetValue(parent, Nothing) = Date.MinValue Then
                Return False
            End If
        End If

        Return True
    End Function
End Class
   
 

Una vez implementada está clase vamos a poder realizar la implementación de la siguiente manera: 

  
    
 PropertyCopier(Of Auto, Vehiculo).Copy(AutoObj, VehiculoObj)  
   
 

Con el código anterior vamos a tener la posibilidad de copiar la información del objeto AutoObj hacia VehiculoObj en una sola línea, este codigo se preparo para que en caso de que una fecha no tenga valor no se copie y lo mismo pasa en caso de traer un valor null. 

Espero les ayude para agilizar sus procesos, cualquier duda no duden en escribirme. Saludos a todos!! 

Comentarios

Entradas populares de este blog

Error 403 Forbidden con phpmyadmin y WAMP Server

Número de filas afectadas por instrucción PL/SQL en Oracle [Utilidades].

Como truncar un número decimal en C# sin redondear.