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
Serialization is a concept in which C# class objects are written or serialized to files. Let' say you had a C# class called Tutorial. And the class has 2 properties of ID and Tutorials name. Serializing can be used to directly write the data properties of the Tutorial class to a file.
The Transient and Static Fields Do Not Get Serialized All the static fields belong to the class instead of the object, and the serialization process serializes the object so static fields can not be serialized.
ICollection represents a type of collection. specifying a collection as an ICollection allows you to use any type of collection in your code that implements the ICollection interface.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With