簡體   English   中英

具有導航屬性的XML序列化

[英]XML Serialization with Navigation Properties

我是一位非常新的MVC開發人員,在將類序列化為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; }
}

我從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”調用上給我反映類型錯誤。 沒有它們,它也可以正常工作(我能夠在沒有電話的情況下正確導出用戶列表)。

我想念什么? 有什么我可以做得更好的嗎?

提前致謝!

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

例如,替換為:

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

與:

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

或者,您也可以在UserClass實現IXmlSerializable ,並通過提供自己的序列化邏輯來描述如何序列化此集合。

我設法通過以下方式解決了這個問題:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM