繁体   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