开发者

Serialization of Entity Framework Models with .NET WCF Rest Service

开发者 https://www.devze.com 2022-12-28 00:26 出处:网络
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:

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 unacce开发者_如何学Cptable for use as an external API. What are suggested mechanisms for using EF for the data store but maintaining a simple XML serialization interface?


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号