I have a class as shown below
public class Survey
{
public Survey()
{
SurveyResponses=new List<SurveyResponse>();
}
[Key]
public Guid SurveyId { get; set; }
public string SurveyName { get; set; }
public string SurveyDescription { get; set; }
public virtual ICollection<Question> Questions { get; set; }
public virtual ICollection<SurveyResponse> SurveyResponses { get; set; }
}
The above code gives me following exception
Cannot serialize member 'SurveyGenerator.Survey.Questions' of type 'System.Collections.Generic.ICollection
When i convert the ICollection to List it serializes properly
Since it is POCO of Entity Framework, i cannot convert ICollection to List
From the looks of your class the ICollection properties are defining foreign key relationships? If so, you wouldn't want to be publicly exposing the collections.
For example: If you are following the best practices guide for developing Entity Framework models, then you would have a separate class called "Question" which would wire up your two class together which might look like the following:
public class Question
{
[Key]
public int Id { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public virtual Survey Survey { get; set; }
}
If this was the case, you could quite possibly go round in circles calling the Question -> Survey -> ICollection -> Question
I had a similar incident using EF, MVC3 to implement a REST service and couldn't serialize the ICollection<> object then realised I didn't need to as I would be calling the object separately anyway.
The updated class for your purposes would look like this:
public class Survey
{
public Survey()
{
SurveyResponses=new List<SurveyResponse>();
}
[Key]
public Guid SurveyId { get; set; }
public string SurveyName { get; set; }
public string SurveyDescription { get; set; }
[XmlIgnore]
[IgnoreDataMember]
public virtual ICollection<Question> Questions { get; set; }
[XmlIgnore]
[IgnoreDataMember]
public virtual ICollection<SurveyResponse> SurveyResponses { get; set; }
}
I hopes this helps you out.