I am sure that for most of you this will be back to the basics but I had this exception yesterday:
Type 'System.Linq.Enumerable+WhereSelectEnumerableIterator`2[ClassA,ServiceClassA]' cannot be serialized. Consider marking it with the DataContractAttribute attribute, and marking all of its members you want serialized with the DataMemberAttribute attribute. See the Microsoft .NET Framework documentation for other supported types.
That I couldn’t find a solution for in Google, though I solved it fairly easily.
The situation was this I had a service lets just call it ClassService with this method:
- [ServiceContract]
- public interface IClassService
- {
- void SomeMethod(ServiceEntity entity);
- }
ServiceEntity was defined as:
- [DataContract]
- public class ServiceEntity
- {
- [DataMember]
- public IEnumerable<ServiceClassA> As { get; set; }
- }
- [DataContract]
- public class ServiceClassA { }
Now the client looked something like:
- public IClassService ClassService { get; set; }
- public void CallService(IEnumerable<ClassA> list)
- {
- ClassService.SomeMethod(new ServiceEntity{As = list.Select(Convert)});
- }
- private ServiceClassA Convert(ClassA a)
- {
- return new ServiceClassA();
- }
(just imagine the constructor initializing the ClassService)
Do you see the mistake?
The problem comes from the line:
- ClassService.SomeMethod(new ServiceEntity{As = list.Select(Convert)});
Or most specifically:
- new ServiceEntity{As = list.Select(Convert)}
The problem is that LINQ doesn’t actually executes this query. It wait until you try to do something with it like converting it to a list or try using one of the entities. The IEnumrable actually has the type of 'System.Linq.Enumerable+WhereSelectEnumerableIterator`2[ClassA,ServiceClassA]' which is not a WCF DataCotract.
The solution is fairly easy:
- ClassService.SomeMethod(new ServiceEntity{As = list.Select(Convert).ToList()});
Just use the LINQ query by creating a List out of it is enough.
Keywords: LINQ, WCF, Exception