Resolve ‘Cannot Serialize Parameter of Type’ Issue in WCF

This annoying error keep popping up when my WCF method return a POCO object generated by DbContext generator.

Or, if the method return a collection of POCO objects:

And in Fiddler, it identified as HTTP 504 error:

This problem is caused by serializing problem when WCF method try to serialize DbSet<T> (or ObjectSet<T> in case of using ObjectContext generator) into POCO objects.

To solve this problem, try the following:

Add KnownTypeAttribute to POCO object.

In POCO class, add KnownType attribute. Also, add DataContract and DataMember attribute if not present.

Object type to be passed to KnownType attribute should be all collection objects that are member of the POCO class. In this case, Product.

If the POCO class is generated with T4 template, you might want to modify the template to include these attributes.

[DataContract(IsReference = true)]
public partial class Category
    public int Id { get; set; }
    public string Name { get; set; }

    public virtual ICollection<Product> Products { get; set; }

Context Configuration

Disable ProxyCreationEnabled in Context configuration.

For DbContext:

// Return one object.
public Category GetCategory(string id)
    var cId = Convert.ToInt32(id);
    var db = new NorthwindEntities();

    db.Configuration.ProxyCreationEnabled = false;
    return db.Categories.Include("Products").First(x => x.Id == cId);

// Return collection of objects
public IEnumerable<Category> GetCategories()
    var db = new NorthwindEntities();

    db.Configuration.ProxyCreationEnabled = false;
    return db.Categories.Include("Products").ToList();

In the case of using ObjectContext, the configuration is:

var context = new POCEntities();

context.ContextOptions.ProxyCreationEnabled = false;

Why we need to disable POCO proxies?

What is Persistence Ignorance?

In Entity Framework, Persistence Ignorance is defined as (MSDN):

An object that does not contain any logic that is related to data storage.

In his book “Applying Domain Driven Design and Patterns”, Jimmy Nilsson (also refers it as POCOs) defines as:

…ordinary classes where you focus on the business problem at hand without adding stuff for infrastructure-related reasons. … The classes should focus on the business problem at hand. Nothing else should be in the classes in the Domain Model.

Persistence ignorance object, or POCO, looks like this (notice there is no any constructor or method in this class):

public partial class Task
    public int Id { get; set; }
    public string Title { get; set; }
    public string Note { get; set; }
    public DateTime DueDate { get; set; }
    public DateTime EndDate { get; set; }
    public int PriorityId { get; set; }
    public int StatusId { get; set; }
    public int ResponsibilityId { get; set; }