When using Entity Framework, how do you serialize properties of type ICollectionT>?

deserialization entity-framework serialization

Question

I'm in the class listed 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 code above throws the following error for me

Cannot serialize member 'SurveyGenerator.Survey.Questions' of type 'System.Collections.Generic.ICollection

I can successfully serialize the ICollection when I convert it to a List.

I am unable to change it from ICollection to List since it is a POCO of Entity Framework.

1
12
9/21/2011 5:53:32 PM

Popular Answer

According to your class's appearance, the ICollection attributes define foreign key associations. If so, you wouldn't want to make the collections available to the public.

According to the best practices manual for creating Entity Framework models, for instance, you would create a second class named "Question" that would connect your two classes, and it may look something like this:

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 were the case, you may end up contacting the Question, Survey, ICollection, and back to the Question.

In a similar event, I realized I didn't need to serialize the ICollection> object since I would be calling it independently otherwise. I was using EF, MVC3 to construct a REST service.

For your needs, the revised class would 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 hope this is useful to you.

2
11/9/2011 7:57:12 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow