如何在使用Entity Framework时序列化ICollection <T>类型的属性

tah*_*ala 12 serialization entity-framework deserialization

我有一个课程,如下所示

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; }
    }
Run Code Online (Sandbox Code Playgroud)

上面的代码给了我以下异常

无法序列化'System.Collections.Generic.ICollection类型的成员'SurveyGenerator.Survey.Questions'

当我将ICollection转换为List时,它正确地序列化

由于它是实体框架的POCO,我无法将ICollection转换为List

Mat*_*ull 3

从类的外观来看,ICollection 属性正在定义外键关系?如果是这样,您就不想公开展示这些藏品。

例如:如果您遵循开发实体框架模型的最佳实践指南,那么您将有一个名为“Question”的单独类,它将您的两个类连接在一起,可能如下所示:

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; }
}
Run Code Online (Sandbox Code Playgroud)

如果是这种情况,您很可能会绕圈调用“问题”->“调查”->“ICollection”->“问题”

我使用 EF、MVC3 实现 REST 服务时遇到了类似的事件,并且无法序列化 ICollection<> 对象,然后意识到我不需要这样做,因为无论如何我都会单独调用该对象。

根据您的目的更新的类将如下所示:

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; }
}
Run Code Online (Sandbox Code Playgroud)

我希望这对你有帮助。