C# 实体框架中的C XmlSerializer
我有两门课:C# 实体框架中的C XmlSerializer,c#,entity-framework,xml-serialization,C#,Entity Framework,Xml Serialization,我有两门课: [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 {
[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; }
}
现在我想将数据导出到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);
它抛出了一个错误:
无效操作异常:类型System.Data.Entity.DynamicProxies.A_08D7BCB892E27DE8C323420E8F0F2B2D3B9E2DAC9F6A16不是预期的。使用XmlInclude或SoapInclude属性指定静态未知的类型
怎么了?我试图搜索类似的主题,但这些解决方案对我不起作用
编辑:预期结果:
<A>
<Id>1</Id>
<Items>
<Item><Id>20</Id></Item>
</Items>
</A>
<A>
..
</A>
也许应该是
public virtual DbSet<A> A{ get; set; }
public IQueryable<A> GetA()
{
return A.AsNoTracking();
}
您可能会遇到此错误,因为实体框架使用项的代理替换项集合以支持延迟加载。 XmlSerializer不需要动态生成的代理类型,因此会出现错误
您可能可以通过为该Items集合属性启用延迟加载来解决此问题。请记住,通过关闭延迟加载,Items集合将始终填充,因此在某些情况下,它可能会给您带来一些意外的性能影响。看起来不错。没有错。还有没有其他你没有提供的细节呢?几乎就这些了,只是那些类有更多的属性,但只有基本类型。准备好了,但也有同样的错误。我还更新了我的问题,我正在序列化一个类的列表。这会有用的。那么,请尝试关闭代理创建。DbContext.Configuration.ProxyCreationEnabled=false;还有,已经试过了。这会停止抛出错误,但为空。也许您可以尝试深度复制,然后序列化它。这一行导致了该错误:public virtual A{get;set;}不知道如何修复它。是的,我刚刚解决了。我只需要关闭它并手动包含项目。否则将出现延迟加载循环。
public virtual DbSet<A> A{ get; set; }
public IQueryable<A> GetA()
{
return A.AsNoTracking();
}