tags:

views:

405

answers:

4

I have two classes generated by LINQ2SQL both from the same table so they have the exact same properties.

I want to convert / cast a object to the other class. what's the easiest way to do this?

I know I can just manually assign each property, but that is a lot of code.

+1  A: 

You are going to have to either do this by hand, or use a flexible serialization framework to work around this. Its possible you could use the built-in json serializer (export to json, then import from json). Or even the XmlSerializer.

Sam Saffron
+1  A: 

MiscUtil has some code to do this using Expression - for example:

Foo foo = ...
Bar bar = PropertyCopy<Bar>.CopyFrom(foo);
Marc Gravell
+2  A: 

You can use serialization to make the copy pretty easily by creating a SerializationBinder. This will allow you to deserialize from one type to another.

class MySerializationBinder : SerializationBinder
{

    public override Type BindToType(string assemblyName, string typeName) 
    {
          Type typeToDeserialize = null;    

          // To return the type, do this:
          if(typeName == "TypeToConvertFrom")
          {
               typeToDeserialize = typeof(TypeToConvertTo);
          }

          return typeToDeserialize;
    }
}

As long as the type properties line up you can use this to Serialize the From type and then deserialize into the To type using a BinaryFormatter and setting the Binder property to an instance of your binder class. If you have several types of objects you can use one Binder to cover all the different types.

Reflection is another option that you can look into to solve this problem. If the property names are exactly the same you could write a simple method that takes values from one property and assigns to the property of the same name.

public static void CopyObject(object source, object destination)
{
   var props = source.GetType().GetProperties();

   foreach (var prop in props)
   {
       PropertyInfo info = destination.GetType().GetProperty(prop.Name);
       if (info != null)
       {
           info.SetValue(destination, prop.GetValue(source, null), null);
       }
   }
}
Brian ONeil
A: 

You can create an interface that has the properties of your linq to sql classes and have both implement the interface.

namespace 
{
 public partial class MyClassA : IInterfaceName
 {
 }

 public partial class MyClassB : IInterfaceName
 {
 }

 public interface IInterfaceName
 {
   string PropertyA {get; set;}
   int PropertyB {get; set;}
   void MyMethod();
 }
}

This will allow you to cast/reference both classes using IInterfaceName. I'm not sure if this is what you want, however, it may be useful. Another option is reloading other object type with the same id.

Chris