简体   繁体   中英

C# XmlSerializer from Entity Framework

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>

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.

Perhaps should be;

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM