簡體   English   中英

如何將XML文檔映射到實體框架對象?

[英]How to map XML document to entity framework object?

我有以下實體框架對象:

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 was unhandled   HResult=-2146233079  
 Message=There was an error reflecting type 'Proj.Accounting.Entity.DocumentStatus'. Source=System.Xml  
 StackTrace:
        at System.Xml.Serialization.XmlReflectionImporter.ImportTypeMapping(TypeModel model, String ns, ImportContext context, String dataType, XmlAttributes a, Boolean repeats, Boolean openModel, RecursionLimiter limiter)
        at System.Xml.Serialization.XmlReflectionImporter.ImportElement(TypeModel model, XmlRootAttribute root, String defaultNamespace, RecursionLimiter limiter)
        at System.Xml.Serialization.XmlReflectionImporter.ImportTypeMapping(Type type, XmlRootAttribute root, String defaultNamespace)
        at System.Xml.Serialization.XmlSerializer..ctor(Type type, String defaultNamespace)
        at System.Xml.Serialization.XmlSerializer..ctor(Type type)
        at Proj.Accounting.Data.XMLObjects.ConvertXmlToClass[T](String xml) in c:\Users\username\Dropbox\Dev\Proj.Accounting\Proj.Accounting.Data\XMLObjects.cs:line 12
        at Proj.Accounting.Data.MainForm.button1_Click(Object sender, EventArgs e) in c:\Users\username\Dropbox\Dev\Proj.Accounting\Proj.Accounting.Data\MainForm.cs:line 36
        at System.Windows.Forms.Control.OnClick(EventArgs e)
        at System.Windows.Forms.Button.OnClick(EventArgs e)
        at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
        at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
        at System.Windows.Forms.Control.WndProc(Message& m)
        at System.Windows.Forms.ButtonBase.WndProc(Message& m)
        at System.Windows.Forms.Button.WndProc(Message& m)
        at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message&m)
        at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
        at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
        at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
        at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
        at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
        at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
        at System.Windows.Forms.Application.Run(Form mainForm)
        at Proj.Accounting.Data.Program.Main() in c:\Users\username\Dropbox\Dev\Proj.Accounting\Proj.Accounting.Data\Program.cs:line 19
        at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
        at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
        at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
        at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
        at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
        at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
        at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
        at System.Threading.ThreadHelper.ThreadStart()   InnerException: System.InvalidOperationException HResult=-2146233079
        Message=Cannot serialize member 'Proj.Accounting.Entity.DocumentStatus.Documents' of type 'System.Collections.Generic.ICollection`1[[Proj.Accounting.Entity.Document,
 Proj.Accounting.Entity, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]', see inner exception for more details.
        Source=System.Xml
        StackTrace:
             at System.Xml.Serialization.StructModel.CheckSupportedMember(TypeDesc typeDesc, MemberInfo member, Type type)
             at System.Xml.Serialization.StructModel.GetPropertyModel(PropertyInfo propertyInfo)
             at System.Xml.Serialization.StructModel.GetFieldModel(MemberInfo memberInfo)
             at System.Xml.Serialization.XmlReflectionImporter.InitializeStructMembers(StructMapping mapping, StructModel model, Boolean openModel, String typeName, RecursionLimiter limiter)
             at System.Xml.Serialization.XmlReflectionImporter.ImportStructLikeMapping(StructModel model, String ns, Boolean openModel, XmlAttributes a, RecursionLimiter limiter)
             at System.Xml.Serialization.XmlReflectionImporter.ImportTypeMapping(TypeModel model, String ns, ImportContext context, String dataType, XmlAttributes a, Boolean repeats, Boolean openModel, RecursionLimiter limiter)
        InnerException: System.NotSupportedException
             HResult=-2146233067
             Message=Cannot serialize member Proj.Accounting.Entity.DocumentStatus.Documents of type
 System.Collections.Generic.ICollection`1[[Proj.Accounting.Entity.Document,
 Proj.Accounting.Entity, Version=1.0.0.0, Culture=neutral,
 PublicKeyToken=null]] because it is an interface.
             InnerException:

一切都說在:

無法序列化類型為Proj.Accounting.Entity.DocumentStatus.Documents成員
System.Collections.Generic.ICollection1 [[Proj.Accounting.Entity.Document,Proj.Accounting.Entity,Version = 1.0.0.0,Culture = neutral,PublicKeyToken = null]], 因為它是接口

接口不可序列化。 將所有ICollection屬性轉換為HashSet類型,以啟用這些項目的序列化。

可序列化

我認為問題在於您的班級Document無法序列化。 序列化對象時,它們的所有字段也必須可序列化。 如果您不想序列化Documents成員,請用[System.Xml.Serialization.XmlIgnoreAttribute]進行標記。

要將對象序列化為XML,請使用序列化方法,並反序列化請使用反序列化方法。 您只需要這些。

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


提示

另外,將您的字符串連接更改為使用StringBuilder。 如果這是測試代碼,請記住您可以在字符串上使用+ =運算符,這將在“清潔代碼”中產生。

例子:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM