2016-12-15 24 views
0

我是一個非常新的MVC開發人員,並且在將我的類序列化到XML時遇到了一些問題。使用導航屬性進行XML序列化

目前,我有以下類:

public class UserClass 
{ 

    public int UserId{ get; set; } 
    public string Email { get; set; } 
    public string FirstName { get; set; } 
    public string LastName { get; set; } 
    public bool LogicalDelete { get; set; } 

    public virtual ICollection<Phone> Phone{ get; set; } 
    [XmlIgnore] 
    public virtual ICollection<EventList> Event{ get; set; } 
} 


public class Phone 
{ 
    public int TelefonosId { get; set; } 
    public string Phone{ get; set; } 
    public bool Mobile{ get; set; } 

    public int UsuarioId { get; set; } 
    public virtual UserClass User { get; set; } 
} 

的串行方法I'm從UserController中調用如下:

public void ExportToXML() 
    { 
     var data = mydb.User.ToList(); 

     Response.ClearContent(); 
     Response.Buffer = true; 
     Response.AddHeader("content-disposition", "attachment;filename=testXML.xml"); 
     Response.ContentType = "text/xml"; 

     var serializer = new System.Xml.Serialization.XmlSerializer(data.GetType()); 
     serializer.Serialize(Response.OutputStream, data); 
    } 

接着而來的問題。當我嘗試序列化時,來自User類的導航屬性在「GetType」調用中給我一個反射類型錯誤。它工作得很好,沒有他們(我能夠正確導出用戶列表,沒有電話)。

我錯過了什麼?有什麼我可以做得更好嗎?

在此先感謝!

+0

()異常,包括異常類型,消息的'輸出,追蹤和內部異常? – dbc

+0

是你得到的錯誤'不能序列化System.Collections.Generic.ICollection 1 [[Phone]]類型的成員UserClass.Phone,因爲它是一個接口。這是我在這裏創建一個[mcve]時看到的錯誤:https://dotnetfiddle.net/NF9BpZ – dbc

+0

是的,這正是錯誤我得到 –

回答

0

我設法解決下列方式問題:假設你得到了一個異常,你可以分享完整的`的ToString

XDocument xmlDocument = new XDocument(
       new XDeclaration("1.0", "utf-8", "yes"), 

       new XComment("Exporting Users to XML"), 

       new XElement("Users", 

        from usu in db.Users.ToList() 
        select new XElement("User", new XElement("Email", usu.Email), 
           new XElement("FirstName", usu.FirstName), 
           new XElement("LastName", usu.LastName), 
           new XElement("Deleted", usu.LogicalDelete), 
            from tel in usu.Phones.ToList() 
            select new XElement("Phone", 
           new XElement("Phone", tel.Phone), 
           new XElement("Mobile", tel.Mobile))) 
          )); 
      xmlDocument.Save("D:\\user.xml"); 
1

您必須用此接口的實現替換接口ICollection

例如,更換:

public virtual ICollection<Phone> Phone{ get; set; } 

有:

public virtual List<Phone> Phone{ get; set; } 

或者你也可以實現在UserClassIXmlSerializable和描述瞭如何通過提供自己的序列化的邏輯序列化此集合。

+0

我這樣做後,我仍然得到同樣的問題(錯誤反映類型)。 –

+0

你可以在你的問題中添加確切的錯誤信息嗎? –