1

I'm using POCO to auto generate my entities from DAL project to Entities project. I currently have no need in creating view classes manually.

However I have one problem - When I try to return a poco object that has navigation properties from a [WebMethod] I get the following error:

Cannot serialize member Entities.City.Customers of type System.Collections.Generic.ICollection1[[Entities.Customer, Entities, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]] because it is an interface.

I tried writing context.ContextOptions.LazyLoadingEnabled = false; and context.ContextOptions.ProxyCreationEnabled = false; to no avail.

if I add [System.Xml.Serialization.XmlIgnore] before the properties, I get no error, but then I lose those properties?

BornToCode
  • 9,495
  • 9
  • 66
  • 83

1 Answers1

2

The message is clear: serialization fails because your Entities.City.Customers member is declared as an interface (ICollection).

The interface does not say anything about the implementing type, it only defines the contract that the implementation should follow. As such, the serializer does not know how to represent the implementation in a serialized format.

You might think that it's not that hard to reflect the type and serialize based on the information you get from introspection, but the problem will be when you try to deserialize from this representation. The same representation could possibly correspond to all implementation types, in which case what should the serializer choose as the concrete type?

There are a few steps to work around this limitation, as you can find in this post: XML serialization of interface property. In your particular case, the simplest way would be to make the Entities.City.Customers member of a concrete type like List<Customer> instead of ICollection<Customer>.

Community
  • 1
  • 1
Bogdan
  • 23,890
  • 3
  • 69
  • 61
  • 1
    Thank you for referring to that informative post. I can't convert `ICollection` to `List` cause POCO creates its navigation properties as ICollection and I can't see how I change this. Perhaps there's no escape rather to create a `CustomerView` class just for serialization (Other solutions looks just as ugly..)? – BornToCode Sep 03 '12 at 21:00
  • @BornToCode: I'm not very familiar with the POCO generator, but it's hard to believe that it does not allow code customizations. Isn't it based on T4 templates? Could you customize those? – Bogdan Sep 05 '12 at 12:08
  • I have this issue too. I changed the t4 template to use List<> instead of ICollection<>. Then the constructor needs to be changed... Then the VerifyCaseInsensitiveTypeUniqueness() method won't compile... Feels like I'm going down the rabbit hole for something that should work out of the box. Does anyone have a better script for this? – Jay Apr 18 '17 at 19:29