views:

463

answers:

2

Hi all,

I have two LINQ objects which have exactly the same columns and I would like to be able to update one with the fields from the other. I first create a new object from some data in a file, then I query the database for an existing item with the same ID. What I would like to be able to do is update the existing objects details with the newly created objects details.

So far the way I have been doing it is to list all the columns and update them manually but as you can see this can cause maintenance headaches.

 With OldCaller
            .ADDRESS = NewCaller.ADDRESS
            .COMPANY = NewCaller.COMPANY
            .CONTACT_HOURS = NewCaller.CONTACT_HOURS
            .CONTACT_NAME = NewCaller.CONTACT_NAME
            .CUSTOMER_ID = NewCaller.CUSTOMER_ID
            .EMAIL_ADDRESS = NewCaller.EMAIL_ADDRESS
            .FAX_NUMBER = NewCaller.FAX_NUMBER
            .FAX_TYPE = NewCaller.FAX_TYPE
            .MOBILE = NewCaller.MOBILE
            .POSTCODE = NewCaller.POSTCODE
            .PUBLIC_ADDRESS = NewCaller.PUBLIC_ADDRESS
            .PUBLIC_TELEPHONE = NewCaller.PUBLIC_TELEPHONE
            .STATE = NewCaller.STATE
            .SUBURB = NewCaller.SUBURB
            .TELEPHONE = NewCaller.TELEPHONE
        End With

I would like to be able to find a way to clean this up a bit. Does anyone know of a better way to do what I need.

Thanks.

+1  A: 

I do this sort of thing when I create an instance of an object from a template. Basically I have a method that iterates over the public properties of the template, finds the corresponding property in the object being created, and invokes the property setter on the new object, all via reflection.

tvanfosson
A: 

I haven't tested this yet but this is what I have come up with.

        Dim _OldCallerProperties = OldCaller.GetType().GetProperties(Reflection.BindingFlags.Public)
        Dim _NewCallerProperties = NewCaller.GetType.GetProperties(Reflection.BindingFlags.Public)

        For Each Prop In _OldCallerProperties
           Dim _matchingProperty = _NewCallerProperties.Where(Function(p) p.Name = Prop.Name).FirstOrDefault
           Dim _newvalue = _matchingProperty.GetValue(_matchingProperty, Nothing)
           Prop.SetValue(Prop, _newvalue, Nothing)
        Next

Like I said I haven't tested it but I'm sure it should work.

Nathan W