我正在尝试使用 DataContractSerializer 将对象序列化为 Xml。我有以下类(class);
[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>();
}
}
但由于某种原因,当我调用方法来序列化对象时,出现以下异常;
Type 'Castle.Proxies.RoomTypeProxy' with data contract name 'RoomTypeProxy:http://schemas.datacontract.org/2004/07/Castle.Proxies' is not expected. Consider using a DataContractResolver or add any types not known statically to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding them to the list of known types passed to DataContractSerializer.
如果我注释掉 Room 类中的属性,它工作正常
[BelongsTo("RoomTypeId")]
[DataMember]
public virtual RoomType RoomType { get; set; }
我不确定为什么会出现异常,因为我已经为 RoomType 添加了 knowtype 属性?我错过了什么,导致了这个问题。
最佳答案
问题是在运行时生成一种类型 (CaSTLe.Proxies.RoomTypeProxy),因此 .NET 对此一无所知。这不是特定于 NHibernate 的问题。如果禁用延迟加载和代理生成,问题就会消失,但我知道这可能很困难。 其他选择是使用其他序列化程序,例如 BinaryFormatter,但我不知道这是否适合您。
关于c# - 为什么我会收到异常 "Consider using a DataContractResolver or add any types not known statically to the list of known types",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22121392/