Click here to Skip to main content
15,881,089 members
Articles / Web Development / ASP.NET
Tip/Trick

WCF, Entity Framework, and Data Contracts

Rate me:
Please Sign up or sign in to vote.
4.00/5 (3 votes)
11 Jan 2013CPOL1 min read 25K   9   5
Expose an Entity Framework class entity as a data contract.

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 

C#
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. Frown | :(

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.  Smile | :)

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.

C#
public static class Converter
{ 
    public static object Convert(object source, object target)
    {
        //find the list of properties in the source object
        Type sourceType = source.GetType();
        IList<PropertyInfo> sourcePropertyList = 
          new List<PropertyInfo>(sourceType.GetProperties());
        //find the list of properties present in the target/destination 

        objectType targetType = target.GetType();
        IList<PropertyInfo> targetPropertyList = 
           new List<PropertyInfo>(targetType.GetProperties());
        //assign value of source object property to the target object.

        foreach (PropertyInfo propertyTarget in targetPropertyList)
        {
            PropertyInfo property = null;
            //find the property which is present in the target object.

            foreach (PropertyInfo propertySource in sourcePropertyList)
            {
                //if find the property store it
                if (propertySource.Name == propertyTarget.Name)
                {
                    property = propertySource;
                    break; 
                }
            }
            //if target property exists in the source
            if (property != null)
            { 
                // take value of source
                object value = property.GetValue(source, null);
                //assign it into the target property 
                propertyTarget.SetValue(target, value, null); 
            }
        }
        return target;
    }
}

How to use Converter?

Suppose you have two entity classes Employee and Person.

C#
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.

C#
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

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
SuggestionAnother solution Pin
Guillaume Leparmentier11-Jan-13 23:54
Guillaume Leparmentier11-Jan-13 23:54 
Your solution is one of the possible solutions, but it has few drawbacks:
- using reflection is not a good solution if you're concerned by performance
Obviously, you can cache somewhere Type descriptions to prevent the framework from inspecting your Types each time you need to convert objects.
- you'll need to expose the same properties between source entity to destination POCO
Here again you could use some kind of mapping configuration file to map a Type's property (name) to another ones

You'll end up writting more and more code which is what, I think, you don't want to Smile | :)


In one of my current projects, we use T4 to customize generated classes and decorate them with DataContract and DataMember attributes. This has solved the two issues described above, and let us (re)generate entities that could be exposed by WCF without writting code.

Well, it's just a suggestion Big Grin | :-D
QuestionThere are tools for this task Pin
Klaus Luedenscheidt11-Jan-13 17:23
Klaus Luedenscheidt11-Jan-13 17:23 
AnswerRe: There are tools for this task Pin
Thomas Eyde12-Jan-13 11:52
Thomas Eyde12-Jan-13 11:52 
AnswerRe: There are tools for this task Pin
ffernandez2313-Jan-13 3:04
ffernandez2313-Jan-13 3:04 
AnswerRe: There are tools for this task Pin
Mike Lang14-Jan-13 4:51
Mike Lang14-Jan-13 4:51 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.