Background
I have created a WCF service using Entity Framework. My
problem is how can I expose Entity Framework class entity as a data contract? I
tried to find out the solution on the internet but no luck.
I
found a few articles that suggested me to create custom entity classes with data
contract attribute and expose these custom entity classes to the outer world.
In each custom classes create a method (example: ConvertTo) that will accept an
object of entity framework class and convert it into the custom class object.
Example
CustomClass ConvertTo(EntityClass objEntityClass)
{
this.Property1 = objEntityClass.Property1;
this.Property2 = objEntityClass.Property2;
….
}
Writing ConverTo method in each of the class is a time taken job. It can be written for
few classes but not when the number is huge. It is very boring job.
After
too many brainstorming I found one solution where I don’t need to write
ConverTo method in each of the custom class. I just wrote a small piece of code
which is responsible for translating the class. I wanted to share it with you
all.
I
have written a code which can take the object of source and destination and
copy the property value of source object to the destination object.
public static class Converter
{
public static object Convert(object source, object target)
{
Type sourceType = source.GetType();
IList<PropertyInfo> sourcePropertyList =
new List<PropertyInfo>(sourceType.GetProperties());
objectType targetType = target.GetType();
IList<PropertyInfo> targetPropertyList =
new List<PropertyInfo>(targetType.GetProperties());
foreach (PropertyInfo propertyTarget in targetPropertyList)
{
PropertyInfo property = null;
foreach (PropertyInfo propertySource in sourcePropertyList)
{
if (propertySource.Name == propertyTarget.Name)
{
property = propertySource;
break;
}
}
if (property != null)
{
object value = property.GetValue(source, null);
propertyTarget.SetValue(target, value, null);
}
}
return target;
}
}
How to use Converter?
Suppose you have two entity classes Employee and Person.
public class Employee
{
public string Fname {get;set;}
public string Lname {get;set;}
}
public class Person
{
public string Fname {get;set;}
public string Lname {get;set;}
public string Address {get;set;}
}
Now we have an object of Employee and want to copy the value of object employee to the object of Person.
public static class ConverterTest
{
public static void Main(string[] argc)
{
Employee employee = new Employee() { Fname = "Jitendra", Lname = "Kumar" };
Person person = new Person();
person = Converter.Convert(employee,person) as Person;
Console.WriteLine(string.Format("{0} : {1} : {2}", person.Fname,
person.Lname, object.Equals(person.Address, null) ? "" : person.Address));
Console.WriteLine("Completed");
Console.Read();
}
}
Result
Jitendra : Kumar :
Completed