为什么我会收到异常“考虑使用DataContractResolver或将任何静态未知的类型添加到已知类型列表中”

时间:2014-03-01 22:44:58

标签: c# wcf nhibernate datacontractserializer castle-activerecord

我正在尝试使用DataContractSerializer将对象序列化为Xml。我有以下课程;

[ActiveRecord(Lazy = true)]
[KnownType(typeof(RoomType))]
[DataContract]
public class Room : ActiveRecordBase<Room>
{
    [PrimaryKey]
    [DataMember]
    public virtual Int64 RoomId { get; protected set; }

    [BelongsTo("RoomTypeId")]
    [DataMember]
    public virtual RoomType RoomType { get; set; }

    [Property]
    [DataMember]
    public virtual Int64 HotelId { get; set; }

    [Property]
    [DataMember]
    public virtual string Name { get; set; }

    [Property]
    [DataMember]
    public virtual string Description { get; set; }

    public static Room[] FindByHotelId(Int64 HotelId)
    {
        return (Room[])FindAllByProperty(typeof(Room), "HotelId", HotelId);
    }
}

RoomType类是

[ActiveRecord(Lazy = true)]
[DataContract]
public class RoomType : ActiveRecordBase<RoomType>
{
    [PrimaryKey]
    [DataMember]
    public virtual int RoomTypeId { get; protected set; }

    [Property]
    [DataMember]
    public virtual string Name { get; set; }

}

我使用以下方法序列化对象

    internal static XElement ObjectToXElement<T>(T source)
    {
        XDocument oXDocument = new XDocument();

        try
        {
            using (var writer = oXDocument.CreateWriter())
            {
                // write xml into the writer
                var serializer = new DataContractSerializer(source.GetType());
                serializer.WriteObject(writer, source);
            }
        }
        catch(Exception e)
        {
            using (var writer = oXDocument.CreateWriter())
            {
                // write xml into the writer
                var serializer = new DataContractSerializer(oError.GetType());
                serializer.WriteObject(writer, oError);
            }
        }

        return oXDocument.Root;
    }

我正在序列化的实际对象是;

[KnownType(typeof(List<Room>))]
[KnownType(typeof(RoomType))]
[DataContract]
public class RoomTypeResponse
{
    [DataMember]
    public int Code { get; set; }

    [DataMember]
    public string Message { get; set; }

    [DataMember]
    public List<Room> Rooms { get; set; }

    public RoomTypeResponse()
    {
        this.Rooms = new List<Room>();
    }
}

但由于某些原因,当我调用该方法来序列化该对象时,我得到以下异常;

  

使用数据合约名称键入“Castle.Proxies.RoomTypeProxy”   'RoomTypeProxy:http://schemas.datacontract.org/2004/07/Castle.Proxies'   不是预期的。考虑使用DataContractResolver或添加任何   静态地知道已知类型列表的类型 - 例如,   通过使用KnownTypeAttribute属性或将它们添加到   传递给DataContractSerializer的已知类型列表。

如果我在Room类中注释掉该属性,它可以正常工作

[BelongsTo("RoomTypeId")]
[DataMember]
public virtual RoomType RoomType { get; set; }

我不知道为什么我会收到异常,因为我已经为RoomType添加了knowtype属性?我错过了什么,这导致了这个问题。

1 个答案:

答案 0 :(得分:2)

问题是在运行时生成一种类型(Castle.Proxies.RoomTypeProxy),因此.NET对此一无所知。这不是NHibernate特有的问题。如果你禁用延迟加载和代理生成,问题就会消失,但我知道这可能很难。 其他选项是使用另一个序列化程序,如BinaryFormatter,但我不知道这是否适合你。