序列化包含派生类的 IEnumerable:循环引用问题 [英] Serializing IEnumerable Containing Derived classes: Circular Reference Issue

查看:43
本文介绍了序列化包含派生类的 IEnumerable:循环引用问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用以下代码序列化 IEnumerable.我收到以下异常.

I am trying to serialize IEnumerable using the following code. I am getting the following exception.

生成 XML 文档时出错.在序列化 DBML_Project.FixedBankAccount 类型的对象时检测到循环引用."}.

There was an error generating the XML document. "A circular reference was detected while serializing an object of type DBML_Project.FixedBankAccount."}.

为什么会出现这个错误?如何纠正?

Why does this error come? How to correct it?

注意:我已经在使用 InheritanceMapping 属性.

Note: I am already using InheritanceMapping attribute.

public class BankAccountAppService
{
    public RepositoryLayer.ILijosBankRepository AccountRepository { get; set; }

    public void FreezeAllAccountsForUser(int userId)
    {
        IEnumerable<DBML_Project.BankAccount> accounts = AccountRepository.GetAllAccountsForUser(userId);
        foreach (DBML_Project.BankAccount acc in accounts)
        {
            acc.Freeze();
        }

        System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();
        System.Xml.XPath.XPathNavigator nav = xmlDoc.CreateNavigator();

        using (System.Xml.XmlWriter writer = nav.AppendChild())
        {
            System.Xml.Serialization.XmlSerializer ser = new System.Xml.Serialization.XmlSerializer(typeof(List<DBML_Project.BankAccount>)); 
            ser.Serialize(writer, accounts);
        }


    }

}

namespace DBML_Project
{
[System.Xml.Serialization.XmlInclude(typeof(FixedBankAccount))]
[System.Xml.Serialization.XmlInclude(typeof(SavingsBankAccount))]
public  partial class BankAccount
{
    //Define the domain behaviors
    public virtual void Freeze()
    {
        //Do nothing
    }
}

public class FixedBankAccount : BankAccount
{

    public override void Freeze()
    {
        this.Status = "FrozenFA";
    }
}

public class SavingsBankAccount : BankAccount
{

    public override void Freeze()
    {
        this.Status = "FrozenSB";
    }
}  
}

使用 LINQ to SQL 自动生成的类

Autogenerated Class using LINQ to SQL

[global::System.Data.Linq.Mapping.TableAttribute(Name="dbo.BankAccount")]
[InheritanceMapping(Code = "Fixed", Type = typeof(FixedBankAccount), IsDefault = true)]
[InheritanceMapping(Code = "Savings", Type = typeof(SavingsBankAccount))]
public partial class BankAccount : INotifyPropertyChanging, INotifyPropertyChanged

推荐答案

使用数据契约序列化器代替 xmlserializer:http://jameskovacs.com/2006/11/18/going-around-in-circles-with-wcf/

Use the data contract serializer instead of the xmlserializer: http://jameskovacs.com/2006/11/18/going-around-in-circles-with-wcf/

这篇关于序列化包含派生类的 IEnumerable:循环引用问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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