【问题标题】:How to map XML document to entity framework object?如何将 XML 文档映射到实体框架对象?
【发布时间】:2015-12-02 15:37:07
【问题描述】:

我有以下实体框架对象:

namespace Proj.Accounting.Entity
{
    using System;
    using System.Collections.Generic;
    using System.Xml.Serialization;

    public partial class DocumentStatus
    {
        public DocumentStatus()
        {
            this.Documents = new HashSet<Document>();
            this.DocumentsTrackings = new HashSet<DocumentsTracking>();
            this.DocumentsTrackingChildDocuments = new HashSet<DocumentsTrackingChildDocument>();
        }
        [XmlElement("StateId")]
        public int StateId { get; set; }
        [XmlElement("StateName")]
        public string StateName { get; set; }
        [XmlElement("GroupId")]
        public Nullable<int> GroupId { get; set; }

        public virtual ICollection<Document> Documents { get; set; }
        public virtual ICollection<DocumentsTracking> DocumentsTrackings { get; set; }
        public virtual ICollection<DocumentsTrackingChildDocument> DocumentsTrackingChildDocuments { get; set; }
    }
}

我有以下类将实体与 xml 字段映射(不是那样工作的):

using System;
using System.Collections;
using System.IO;
using System.Xml.Serialization;

namespace Proj.Accounting.Data
{
    class XMLObjects
    {
        public static T ConvertXmlToClass<T>(string xml)
        {
            var serializer = new XmlSerializer(typeof(T));
            return (T)serializer.Deserialize(new StringReader(xml));
        }
    }
}

以及我用来映射数据的方法:

private void button1_Click(object sender, EventArgs e)
{
    string xml = "";
    xml +=  "<?xml version=\"1.0\" encoding=\"UTF - 8\"?>";
    xml +=  "<root>";
    xml += " <success>true</success>";
    xml +=  " <data>";
    xml += " <item>";
    xml += " <StateId>0</StateId>";
    xml += " <StateName>Шаблон</StateName>";
    xml += " <GroupId>0</GroupId>";
    xml += " </item>";
    xml +=  "</root>";
    DocumentStatus documentStatus = new DocumentStatus();
    documentStatus = XMLObjects.ConvertXmlToClass<DocumentStatus>(xml);
    int a = 0;
}

我收到以下异常

System.InvalidOperationException 未处理 HResult=-2146233079 消息=反映类型“Proj.Accounting.Entity.DocumentStatus”的错误。源=System.Xml 堆栈跟踪: 在 System.Xml.Serialization.XmlReflectionImporter.ImportTypeMapping(TypeModel 模型,字符串 ns,ImportContext 上下文,字符串数据类型,XmlAttributes a,布尔重复,布尔 openModel,RecursionLimiter 限制器) 在 System.Xml.Serialization.XmlReflectionImporter.ImportElement(TypeModel 模型,XmlRootAttribute 根,字符串 defaultNamespace,RecursionLimiter 限制器) 在 System.Xml.Serialization.XmlReflectionImporter.ImportTypeMapping(类型类型,XmlRootAttribute 根,字符串 defaultNamespace) 在 System.Xml.Serialization.XmlSerializer..ctor(类型类型,字符串 defaultNamespace) 在 System.Xml.Serialization.XmlSerializer..ctor(类型类型) 在 c:\Users\username\Dropbox\Dev\Proj.Accounting\Proj.Accounting.Data\XMLObjects.cs:line 12 中的 Proj.Accounting.Data.XMLObjects.ConvertXmlToClass[T](String xml) 在 Proj.Accounting.Data.MainForm.button1_Click(Object sender, EventArgs e) 在 c:\Users\username\Dropbox\Dev\Proj.Accounting\Proj.Accounting.Data\MainForm.cs:line 36 在 System.Windows.Forms.Control.OnClick(EventArgs e) 在 System.Windows.Forms.Button.OnClick(EventArgs e) 在 System.Windows.Forms.Button.OnMouseUp(MouseEventArgs 事件) 在 System.Windows.Forms.Control.WmMouseUp(消息和 m,MouseButtons 按钮,Int32 点击) 在 System.Windows.Forms.Control.WndProc(消息和 m) 在 System.Windows.Forms.ButtonBase.WndProc(消息和 m) 在 System.Windows.Forms.Button.WndProc(消息和 m) 在 System.Windows.Forms.Control.ControlNativeWindow.OnMessage(消息&m) 在 System.Windows.Forms.Control.ControlNativeWindow.WndProc(消息和 m) 在 System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd,Int32 msg,IntPtr wparam,IntPtr lparam) 在 System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(味精和味精) 在 System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID,Int32 原因,Int32 pvLoopData) 在 System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 原因,ApplicationContext 上下文) 在 System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 原因,ApplicationContext 上下文) 在 System.Windows.Forms.Application.Run(窗体 mainForm) 在 c:\Users\username\Dropbox\Dev\Proj.Accounting\Proj.Accounting.Data\Program.cs:line 19 中的 Proj.Accounting.Data.Program.Main() 在 System.AppDomain._nExecuteAssembly(RuntimeAssembly 程序集,字符串 [] 参数) 在 System.AppDomain.ExecuteAssembly(字符串 assemblyFile,证据 assemblySecurity,String [] args) 在 Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly() 在 System.Threading.ThreadHelper.ThreadStart_Context(对象状态) 在 System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext,ContextCallback 回调,对象状态,布尔值 preserveSyncCtx) 在 System.Threading.ExecutionContext.Run(ExecutionContext executionContext,ContextCallback 回调,对象状态,布尔值 preserveSyncCtx) 在 System.Threading.ExecutionContext.Run(ExecutionContext executionContext,ContextCallback 回调,对象状态) 在 System.Threading.ThreadHelper.ThreadStart() InnerException: System.InvalidOperationException HResult=-2146233079 消息=无法序列化类型为“System.Collections.Generic.ICollection”的成员“Proj.Accounting.Entity.DocumentStatus.Documents”1 [[Proj.Accounting.Entity.Document, Proj.Accounting.Entity,Version=1.0.0.0,Culture=neutral,PublicKeyToken=null]]',有关更多详细信息,请参阅内部异常。 源=System.Xml 堆栈跟踪: 在 System.Xml.Serialization.StructModel.CheckSupportedMember(TypeDesc typeDesc,MemberInfo 成员,类型类型) 在 System.Xml.Serialization.StructModel.GetPropertyModel(PropertyInfo propertyInfo) 在 System.Xml.Serialization.StructModel.GetFieldModel(MemberInfo memberInfo) 在 System.Xml.Serialization.XmlReflectionImporter.InitializeStructMembers(StructMapping 映射,StructModel 模型,Boolean openModel,String typeName,RecursionLimiter 限制器) 在 System.Xml.Serialization.XmlReflectionImporter.ImportStructLikeMapping(StructModel 模型,字符串 ns,布尔 openModel,XmlAttributes a,RecursionLimiter 限制器) 在 System.Xml.Serialization.XmlReflectionImporter.ImportTypeMapping(TypeModel 模型,字符串 ns,ImportContext 上下文,字符串数据类型,XmlAttributes a,布尔重复,布尔 openModel,RecursionLimiter 限制器) 内部异常:System.NotSupportedException H结果=-2146233067 Message=无法序列化成员 Proj.Accounting.Entity.DocumentStatus.Documents 类型 System.Collections.Generic.ICollection`1[[Proj.Accounting.Entity.Document, Proj.Accounting.Entity,版本=1.0.0.0,文化=中性, PublicKeyToken=null]] 因为它是一个接口。 内部异常:

【问题讨论】:

    标签: c# .net entity-framework xml-serialization entity-framework-6


    【解决方案1】:

    一切都在:

    无法序列化成员 Proj.Accounting.Entity.DocumentStatus.Documents 类型
    System.Collections.Generic.ICollection1[[Proj.Accounting.Entity.Document, Proj.Accounting.Entity,版本=1.0.0.0,文化=中性, PublicKeyToken=null]] 因为它是一个接口

    接口不可序列化。将您的所有 ICollection 属性转换为类型 HashSet 以启用这些项目的序列化。

    【讨论】:

      【解决方案2】:

      可序列化

      我认为问题在于您的类 Document 不可序列化。当您序列化一个对象时,它们的所有字段也必须是可序列化的。如果您不想序列化 Documents 成员,请将其标记为 [System.Xml.Serialization.XmlIgnoreAttribute]

      要将 Object 序列化为 XML,请使用 Serialize 方法,而要反序列化,请使用 Deserialize 方法。你不需要更多。

      更多信息:https://msdn.microsoft.com/es-es/library/system.xml.serialization.xmlserializer(v=vs.110).aspx


      提示

      另外,更改您的字符串连接以使用 StringBuilder。如果这是测试代码,请记住您可以在字符串上使用 += 运算符,这会导致 Clean Code。

      示例:

      string xml = "";
      xml = xml + "<?xml version=\"1.0\" encoding=\"UTF - 8\"?>";
      xml = xml + "<root>";
      

      使用 += 运算符(结果相同但更简洁)

      string xml = "";
      xml += "<?xml version=\"1.0\" encoding=\"UTF - 8\"?>";
      xml += "<root>";
      

      使用 StringBuilder(最好最快的方式)

      StringBuilder xml = new StringBuilder();
      xml.Append("<?xml version=\"1.0\" encoding=\"UTF - 8\"?>");
      xml.Append("<root>");
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-08-17
        • 1970-01-01
        • 1970-01-01
        • 2010-10-09
        • 2020-10-31
        • 2015-02-15
        相关资源
        最近更新 更多