C# XmlSerializer from Entity Framework

别来无恙 提交于 2019-12-13 03:50:30

问题


I have 2 classes:

 [XmlInclude(typeof(Item))]
 public class A
 {
     public int Id { get; set; }

     [XmlArray("Items")]
     [XmlArrayItem("Item")]
     public virtual List<Item> Items { get; set; } = new List<Item>();
 }

 public class Item
 {
     public int Id { get; set; }
     [XmlIgnore]
     public virtual A a { get; set; }
 }

I'm using this method inside my DbContext:

public virtual DbSet<A> A { get; set; }

public IQueryable<A> GetA()
{
      return A;
}

Now I want to export data to XML:

Type[] types = { typeof(Item) };

var aElements = GetA().ToList();

System.Xml.Serialization.XmlSerializer writer =
     new System.Xml.Serialization.XmlSerializer(aElements.GetType(), types);

writer.Serialize(file, aElements);

And it throws an error:

InvalidOperationException: The type System.Data.Entity.DynamicProxies.A_08D7BCCB892E27DE8C32342A0E8F0F2B2D3B9E2DAC9F6A16 was not expected. Use the XmlInclude or SoapInclude attribute to specify types that are not known statically.

What's wrong? I tried to search similar topics, but those solutions doesn't work for me.

Edit: expected result:

<A>
  <Id>1</Id>
  <Items>
     <Item><Id>20</Id></Item>
  </Items>
</A>
<A>
  ..
</A>

回答1:


You're probably getting this error because Entity Framework substitutes your collection of Items with Proxies to Items to support lazy loading. The XmlSerializer doesn't expect the dynamically generated proxy type, hence the error.

You can probably solve this by turning of Lazy Loading for that Items collection property. Keep in mind that, by turning off lazy-loading, the Items collection will always be populated, so it might give you some unexpected performance hits in some cases.




回答2:


Perhaps should be;

public virtual DbSet<A> A{ get; set; }
public IQueryable<A> GetA()
{
      return A.AsNoTracking();
}


来源:https://stackoverflow.com/questions/47497769/c-sharp-xmlserializer-from-entity-framework

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!