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?


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s