【发布时间】:2012-07-03 17:22:06
【问题描述】:
我正在尝试使用以下代码序列化 IEnumerable。我收到以下异常。
生成 XML 文档时出错。 “在序列化 DBML_Project.FixedBankAccount 类型的对象时检测到循环引用。”}。
为什么会出现这个错误?如何纠正?
注意:我已经在使用 InheritanceMapping 属性了。
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 自动生成的类
[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
【问题讨论】:
-
LINQ-to-SQL 的代码生成器可以发出 DataContractSerializer 注释,并且旨在与 DataContractSerializer 一起使用,而不是 XmlSerializer...
-
@MarcGravell 谢谢。您能否提供用于序列化 IEnumerable 的参考文章/论坛帖子?另外,请注意我已经在使用 InheritanceMapping 属性
-
大多数序列化程序不直接支持
IEnumerable[<T>]。List<T>当然,但那不一样。
标签: c# .net wcf serialization xml-serialization