如何序列化ICollection类型的属性< T>而使用实体框架 [英] How to Serialize property of type ICollection<T> while using Entity Framework

查看:337
本文介绍了如何序列化ICollection类型的属性< T>而使用实体框架的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类,如下所示

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


无法序列化
'System.Collections.Generic.ICollection

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

的成员'SurveyGenerator.Survey.Questions'

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

When i convert the ICollection to List it serializes properly

由于它是Entity Framework的POCO,我无法将ICollection转换为List

Since it is POCO of Entity Framework, i cannot convert ICollection to List

推荐答案

从您的类的外观,ICollection属性正在定义外键关系?如果是这样,你不想公开露出这些集合。

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; }
}

如果是这样的话,问题 - >调查 - > ICollection - >问题

If this was the case, you could quite possibly go round in circles calling the Question -> Survey -> ICollection -> Question

我有一个类似的事件,使用EF,MVC3实现REST服务,无法序列化ICollection<>对象然后意识到我不需要,因为我会单独调用对象。

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; }
}

我希望这可以帮助你。

这篇关于如何序列化ICollection类型的属性&lt; T&gt;而使用实体框架的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆