XmlSerializer (c#) 报告存在反映类型的错误 (type = List)

发布于 2024-08-27 06:38:03 字数 3985 浏览 5 评论 0原文

有人可以帮忙吗?

我有一种将对象转换为数据集的方法。在本例中,对象是集合类的集合(使用 LIST)

这是代码,但在 XmlSerializer formatter= ... 行上出现以下错误,

这是错误

存在反映类型“System.Collections”的 错误.Generic.List`1[MyNameSpace.Model.InformeVehiculo]'。

    public static DataSet TransformObjectToDataSet(System.Type type, object datos, string nombre)
    {
        XmlSerializer formatter = new XmlSerializer(type, "Coleccion" + nombre);
        MemoryStream buffer = new MemoryStream();
        formatter.Serialize(buffer, datos);
        buffer.Position = 0;
        DataSet dtsDatos = new DataSet(nombre);
        dtsDatos.ReadXml(buffer);

        return dtsDatos;
    }

我像这样调用方法

   TransformObjectToDataSet(typeof(List<InformeVehiculo>), objColeccionInformeVehiculo, "ColeccionInformeVehiculo");

objColeccionInformeVehiculo 是一个列表

我有点迷失,有谁知道为什么它失败

编辑

进一步查看 InnerExeption 后,最后一个显示以下内容

 {"Cannot serialize member MyNameSpace.Model.ObjectChangeTracker.ObjectsRemovedFromCollectionProperties of type MyNameSpace.Model.ObjectsRemovedFromCollectionProperties, because it implements IDictionary."}

实际上在 InformeVehiculo 内我有将其扩展为保存对 InformeContracto 的引用(使用部分类,它是最初由实体框架创建的模型)

InformeContrato 是其失败的地方。

我的类

 public partial class InformeContrato : IObjectWithChangeTracker, INotifyPropertyChanged

InformeContrato 并不存在,与 InformeVehiculo 不同,InformeVehiculo 作为实体框架创建的部分类存在。因此,我手动创建了 InformeContrato 并插入了 ChangeTracking 内容。

再往下,我有一个从实体框架创建的模型复制的区域。

    #region ChangeTracking

    protected virtual void OnPropertyChanged(String propertyName)
    {
        if (ChangeTracker.State != ObjectState.Added && ChangeTracker.State != ObjectState.Deleted)
        {
            ChangeTracker.State = ObjectState.Modified;
        }
        if (_propertyChanged != null)
        {
            _propertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    protected virtual void OnNavigationPropertyChanged(String propertyName)
    {
        if (_propertyChanged != null)
        {
            _propertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    event PropertyChangedEventHandler INotifyPropertyChanged.PropertyChanged { add { _propertyChanged += value; } remove { _propertyChanged -= value; } }
    private event PropertyChangedEventHandler _propertyChanged;
    private ObjectChangeTracker _changeTracker;

    //[DataMember]
    public ObjectChangeTracker ChangeTracker
    {
        get
        {
            if (_changeTracker == null)
            {
                _changeTracker = new ObjectChangeTracker();
                _changeTracker.ObjectStateChanging += HandleObjectStateChanging;
            }
            return _changeTracker;
        }
        set
        {
            if (_changeTracker != null)
            {
                _changeTracker.ObjectStateChanging -= HandleObjectStateChanging;
            }
            _changeTracker = value;
            if (_changeTracker != null)
            {
                _changeTracker.ObjectStateChanging += HandleObjectStateChanging;
            }
        }
    }

    private void HandleObjectStateChanging(object sender, ObjectStateChangingEventArgs e)
    {
        if (e.NewState == ObjectState.Deleted)
        {
            ClearNavigationProperties();
        }
    }

    protected bool IsDeserializing { get; private set; }

    [OnDeserializing]
    public void OnDeserializingMethod(StreamingContext context)
    {
        IsDeserializing = true;
    }

    [OnDeserialized]
    public void OnDeserializedMethod(StreamingContext context)
    {
        IsDeserializing = false;
        ChangeTracker.ChangeTrackingEnabled = true;
    }

    protected virtual void ClearNavigationProperties()
    {
        //AccesorioContrato.Clear();
    }

    #endregion

Can anyone help?

I have a method for converting an object to a dataset. In this case the object is a collection (using LIST) of a a collection class

Here is the code but it errors with the following error on the line XmlSerializer formatter= ...

This is the error

There was an error reflecting type 'System.Collections.Generic.List`1[MyNameSpace.Model.InformeVehiculo]'.

    public static DataSet TransformObjectToDataSet(System.Type type, object datos, string nombre)
    {
        XmlSerializer formatter = new XmlSerializer(type, "Coleccion" + nombre);
        MemoryStream buffer = new MemoryStream();
        formatter.Serialize(buffer, datos);
        buffer.Position = 0;
        DataSet dtsDatos = new DataSet(nombre);
        dtsDatos.ReadXml(buffer);

        return dtsDatos;
    }

I am calling the method like so

   TransformObjectToDataSet(typeof(List<InformeVehiculo>), objColeccionInformeVehiculo, "ColeccionInformeVehiculo");

objColeccionInformeVehiculo is a List

I am a little lost, does anyone know why its failing

EDIT

After looking further down the InnerExeption, the last one displays the following

 {"Cannot serialize member MyNameSpace.Model.ObjectChangeTracker.ObjectsRemovedFromCollectionProperties of type MyNameSpace.Model.ObjectsRemovedFromCollectionProperties, because it implements IDictionary."}

Actually inside the InformeVehiculo i have extended it to hold a reference to InformeContracto (using partial classes, it is a model originally created by entity framework)

InformeContrato is where its failing.

This my class

 public partial class InformeContrato : IObjectWithChangeTracker, INotifyPropertyChanged

InformeContrato did NOT exist unlike InformeVehiculo which existed as a partial class created by entity framework. So I created InformeContrato manually and inserted the changeTracking stuff..

Further down I have a region which i copied from a MODEL created by Entity Framework.

    #region ChangeTracking

    protected virtual void OnPropertyChanged(String propertyName)
    {
        if (ChangeTracker.State != ObjectState.Added && ChangeTracker.State != ObjectState.Deleted)
        {
            ChangeTracker.State = ObjectState.Modified;
        }
        if (_propertyChanged != null)
        {
            _propertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    protected virtual void OnNavigationPropertyChanged(String propertyName)
    {
        if (_propertyChanged != null)
        {
            _propertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    event PropertyChangedEventHandler INotifyPropertyChanged.PropertyChanged { add { _propertyChanged += value; } remove { _propertyChanged -= value; } }
    private event PropertyChangedEventHandler _propertyChanged;
    private ObjectChangeTracker _changeTracker;

    //[DataMember]
    public ObjectChangeTracker ChangeTracker
    {
        get
        {
            if (_changeTracker == null)
            {
                _changeTracker = new ObjectChangeTracker();
                _changeTracker.ObjectStateChanging += HandleObjectStateChanging;
            }
            return _changeTracker;
        }
        set
        {
            if (_changeTracker != null)
            {
                _changeTracker.ObjectStateChanging -= HandleObjectStateChanging;
            }
            _changeTracker = value;
            if (_changeTracker != null)
            {
                _changeTracker.ObjectStateChanging += HandleObjectStateChanging;
            }
        }
    }

    private void HandleObjectStateChanging(object sender, ObjectStateChangingEventArgs e)
    {
        if (e.NewState == ObjectState.Deleted)
        {
            ClearNavigationProperties();
        }
    }

    protected bool IsDeserializing { get; private set; }

    [OnDeserializing]
    public void OnDeserializingMethod(StreamingContext context)
    {
        IsDeserializing = true;
    }

    [OnDeserialized]
    public void OnDeserializedMethod(StreamingContext context)
    {
        IsDeserializing = false;
        ChangeTracker.ChangeTrackingEnabled = true;
    }

    protected virtual void ClearNavigationProperties()
    {
        //AccesorioContrato.Clear();
    }

    #endregion

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

微凉徒眸意 2024-09-03 06:38:03

IDictionary 不可序列化。标准词典也不是。您将需要实现自定义字典类型才能启用序列化。然后它就会起作用。

EX 用于 XML 序列化:

  [XmlRoot("dictionary")]
public class SerializableDictionary<TKey, TValue>
    : Dictionary<TKey, TValue>, IXmlSerializable
{
    #region IXmlSerializable Members

    public XmlSchema GetSchema()
    {
        return null;
    }

    public void ReadXml(XmlReader reader)
    {
        XmlSerializer keySerializer = new XmlSerializer(typeof (TKey));
        XmlSerializer valueSerializer = new XmlSerializer(typeof (TValue));

        bool wasEmpty = reader.IsEmptyElement;
        reader.Read();

        if (wasEmpty)
            return;

        while (reader.NodeType != XmlNodeType.EndElement)
        {
            reader.ReadStartElement("item");

            reader.ReadStartElement("key");
            TKey key = (TKey) keySerializer.Deserialize(reader);
            reader.ReadEndElement();

            reader.ReadStartElement("value");
            TValue value = (TValue) valueSerializer.Deserialize(reader);
            reader.ReadEndElement();

            Add(key, value);

            reader.ReadEndElement();
            reader.MoveToContent();
        }
        reader.ReadEndElement();
    }

    public void WriteXml(XmlWriter writer)
    {
        XmlSerializer keySerializer = new XmlSerializer(typeof (TKey));
        XmlSerializer valueSerializer = new XmlSerializer(typeof (TValue));

        foreach (TKey key in Keys)
        {
            writer.WriteStartElement("item");

            writer.WriteStartElement("key");
            keySerializer.Serialize(writer, key);
            writer.WriteEndElement();

            writer.WriteStartElement("value");
            TValue value = this[key];
            valueSerializer.Serialize(writer, value);
            writer.WriteEndElement();

            writer.WriteEndElement();
        }
    }

    #endregion 
}

IDictionary is not serializable. Nor are the standard dictionaries. You will need to implement a custom dictionary type to enable serialization. Then it will work.

EX for XML Serialization:

  [XmlRoot("dictionary")]
public class SerializableDictionary<TKey, TValue>
    : Dictionary<TKey, TValue>, IXmlSerializable
{
    #region IXmlSerializable Members

    public XmlSchema GetSchema()
    {
        return null;
    }

    public void ReadXml(XmlReader reader)
    {
        XmlSerializer keySerializer = new XmlSerializer(typeof (TKey));
        XmlSerializer valueSerializer = new XmlSerializer(typeof (TValue));

        bool wasEmpty = reader.IsEmptyElement;
        reader.Read();

        if (wasEmpty)
            return;

        while (reader.NodeType != XmlNodeType.EndElement)
        {
            reader.ReadStartElement("item");

            reader.ReadStartElement("key");
            TKey key = (TKey) keySerializer.Deserialize(reader);
            reader.ReadEndElement();

            reader.ReadStartElement("value");
            TValue value = (TValue) valueSerializer.Deserialize(reader);
            reader.ReadEndElement();

            Add(key, value);

            reader.ReadEndElement();
            reader.MoveToContent();
        }
        reader.ReadEndElement();
    }

    public void WriteXml(XmlWriter writer)
    {
        XmlSerializer keySerializer = new XmlSerializer(typeof (TKey));
        XmlSerializer valueSerializer = new XmlSerializer(typeof (TValue));

        foreach (TKey key in Keys)
        {
            writer.WriteStartElement("item");

            writer.WriteStartElement("key");
            keySerializer.Serialize(writer, key);
            writer.WriteEndElement();

            writer.WriteStartElement("value");
            TValue value = this[key];
            valueSerializer.Serialize(writer, value);
            writer.WriteEndElement();

            writer.WriteEndElement();
        }
    }

    #endregion 
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文