views:

210

answers:

2

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"&gt;
  <EntityKey p1:Id="NCNameString" p1:Ref="NCNameString" xmlns="http://schemas.datacontract.org/2004/07/System.Data.Objects.DataClasses"&gt;
    <EntityContainerName xmlns="http://schemas.datacontract.org/2004/07/System.Data"&gt;String content</EntityContainerName>
    <EntityKeyValues xmlns="http://schemas.datacontract.org/2004/07/System.Data"&gt;
...

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?

A: 

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.

Robert Harvey
+1  A: 

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.

Craig Stuntz
Thanks -- I've been thinking myself in circles about how to best do this and the answer was staring me right in the face the whole time. I'll be implementing something like this in the morning!
Chris Phillips