4

The following class was Auto generated from a template using the Entity Framework Model.

namespace Entities { using System; using System.Collections.Generic; public partial class Country { public Country() { this.Regions = new HashSet<Region>(); } public long CountryId { get; set; } public string Code { get; set; } public string Name { get; set; } public bool Preferred { get; set; } public System.DateTime LastChanged { get; set; } public virtual ICollection<Region> Regions { get; set; } } } 

I have a Wcf web service that returns POX (Xml) and Json only. I am wanting to return my own serialised object like;

public class MyResponseObject { public int RequestId {get;set;} public List<Country> CountryList {get;set;} //other properties } 

But I don't want to return the Regions ICollection.

The object can then be returned using something like

Newtonsoft.Json.JsonConvert.SerializeObject()

Am I best returning my own serialised POCO object in this manner ?

1 Answer 1

8
+50

In projects like these, your classes can be split into two types:

  1. Database entity objects (what Entity Framework works with)
  2. Data contract objects (what WCF or your web-service works with)

While it is possible to use the same objects for both, it is not recommended because the database entity objects are an internal implementation concern that is separate from the external interface (your webservice). You might add or remove columns to your database table and not want your API contracts to change. But usually you'll want to hide information from service-consumers, like a database table Users ( UserId, Password ), you definitely don't want the Password property going out!

Another reason not to is that you later might want to add attributes to your webservice contract classes (e.g. to control output formatting or input validation), adding these to entity objects is painful, if not impossible in some cases.

I know it sounds like a needless duplication of work as the majority of classes will have identical members, but it makes sense from a long-term perspective.

Fortunately tools like AutoMapper can speed-up the process of copying data from your database entity objects to your data contract objects.

Sign up to request clarification or add additional context in comments.

3 Comments

So basically I'd create a POCO class that I populate with data from the entity object. To populate the POCO class object, am I best just iterating through the entity object, populating the POCO class for each iteration ? Can you give me a example please
@Tommo1977 there are tools that can automate that process, AutoMapper is a popular one.
@Tommo1977 Your webservice data-transfer classes are not necessarily POCOs, if they involve any custom inheritance, interfaces or attributes. Jus' saying.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.