实体框架中的C#XmlSerializer [英] C# XmlSerializer from Entity Framework

查看:122
本文介绍了实体框架中的C#XmlSerializer的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有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; }
 }

我在 DbContext中使用此方法

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

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

现在我想将数据导出到XML:

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

它会引发错误:


InvalidOperationException:不应预期类型System.Data.Entity.DynamicProxies.A_08D7BCCB892E27DE8C32342A0E8F0F2B2D3B9E2DAC9F6A16。使用XmlInclude或SoapInclude属性可以指定静态未知的类型。

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.

编辑:预期结果:

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


推荐答案

您可能会收到此错误,因为实体框架替代了您的项目集合,其中包含对项目的代理以支持延迟加载。
XmlSerializer并不期望动态生成的代理类型,因此不会出现错误。

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.

您可能可以通过打开 Items集合属性的延迟加载来解决此问题。 。请记住,通过关闭延迟加载,将始终填充Items集合,因此在某些情况下,它可能会给您带来意想不到的性能影响。

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.

这篇关于实体框架中的C#XmlSerializer的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆