为什么我会收到异常"Consider using a DataContractResolver or add any types not known statically to the list of



我正在尝试使用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属性?我错过了什么,这就是造成这个问题的原因。

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

相关内容

最新更新