简体   繁体   English

实体框架中的C#XmlSerializer

[英]C# XmlSerializer from Entity Framework

I have 2 classes: 我有2节课:

 [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 : 我在我的DbContext使用此方法:

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

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

Now I want to export data to XML: 现在我想将数据导出到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. InvalidOperationException:不应预期类型System.Data.Entity.DynamicProxies.A_08D7BCCB892E27DE8C32342A0E8F0F2B2D3B9E2DAC9F6A16。 Use the XmlInclude or SoapInclude attribute to specify types that are not known statically. 使用XmlInclude或SoapInclude属性可以指定静态未知的类型。

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. 您可能会收到此错误,因为Entity Framework将具有Proxies的Items集合替换为Items以支持延迟加载。 The XmlSerializer doesn't expect the dynamically generated proxy type, hence the error. XmlSerializer不希望动态生成代理类型,因此会出现错误。

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. 请记住,通过关闭延迟加载,将始终填充Items集合,因此在某些情况下,它可能会给您带来一些意想不到的性能影响。

Perhaps should be; 也许应该是;

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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