Chris Phillips
Chris Phillips

Reputation: 12377

Serialization of Entity Framework Models with .NET WCF Rest Service

I'm trying to put together a very simple REST-style interface for communicating with our partners. An example object in the API is a partner, which we'd like to have serialized like this:

<partner>
    <id>ID</id>
    <name>NAME</name>
</partner>

This is fairly simply to achieve using the .NET 4.0 WCF REST template if we simply declare a partner class as:

public class Partner
{
    public int Id {get; set;}
    public string Name {get; set;}
}

But when I use the Entity Framework to define and store Partner objects, the resulting serialization looks something like this:

<Partner p1:Id="NCNameString" p1:Ref="NCNameString" xmlns:p1="http://schemas.microsoft.com/2003/10/Serialization/" xmlns="http://schemas.datacontract.org/2004/07/TheTradeDesk.AdPlatform.Provisioning">
  <EntityKey p1:Id="NCNameString" p1:Ref="NCNameString" xmlns="http://schemas.datacontract.org/2004/07/System.Data.Objects.DataClasses">
    <EntityContainerName xmlns="http://schemas.datacontract.org/2004/07/System.Data">String content</EntityContainerName>
    <EntityKeyValues xmlns="http://schemas.datacontract.org/2004/07/System.Data">
...

This XML is obviously unacceptable for use as an external API. What are suggested mechanisms for using EF for the data store but maintaining a simple XML serialization interface?

Upvotes: 1

Views: 1850

Answers (2)

Craig Stuntz
Craig Stuntz

Reputation: 126547

Just project onto your Partner type, as defined in your question:

var q = from p in Context.Partners
        select new MySerializationTypes.Partner
        {
            Id = p.Id,
            Name = p.Name
        };

...and then serialize that.

Upvotes: 1

Robert Harvey
Robert Harvey

Reputation: 180787

It appears that you will need a set of objects to provide a layer between the EF and your external API.

Although it appears redundant, this is not exactly an unprecedented practice. It is done all the time in the MVC pattern, when you need a layer of abstraction between the view and the underlying data store.

An additional abstraction layer provides you with the ability to define the exact interface you want, with the flexibility and control to interact with EF in precisely the manner you want.

Upvotes: 0

Related Questions