2012-07-03 37 views
0

我正在嘗試使用以下代碼序列化IEnumerable。我收到以下例外情況。序列化IEnumerable包含派生類:循環引用問題

生成XML文檔時發生錯誤。 「在序列化DBML_Project.FixedBankAccount類型的對象時檢測到循環引用。」}。

爲什麼會出現此錯誤?如何糾正?

注意:我已經在使用InheritanceMapping屬性。使用LINQ到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 
+3

的代碼發生器,用於LINQ到SQL可發射的DataContractSerializer註解,並打算用於DataContractSerializer,而不是XmlSerializer ... –

+0

@MarcGravell謝謝。你能否提供一個參考文章/論壇帖子來序列化IEnumerable?另外,請注意,我已經在使用InheritanceMapping屬性 – Lijo

+1

大多數序列化器*不直接支持'IEnumerable []'。 '清單'*當然*,但那是不一樣的。 –

回答

1

使用數據合同串行代替XmlSerializer的

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

自動生成的類: http://jameskovacs.com/2006/11/18/going-around-in-circles-with-wcf/