Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I need to use POCO Classes with Entity Framework 6

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 ?

like image 573
neildt Avatar asked Feb 13 '23 14:02

neildt


1 Answers

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.

like image 117
Dai Avatar answered Feb 19 '23 11:02

Dai