如何使用“一对多”关系序列化两个对象?

时间:2010-08-12 06:26:34

标签: c# .net serialization xml-serialization

我有两个类:LookupLookupItem Lookup有一个名为Items的成员,它是LookupItem的集合。我无法序列化LookupLookupItem。第一次出现错误The type LookupItem was not expected. Use the XmlInclude or SoapInclude attribute to specify types that are not known statically.,第二次出现错误A circular reference was detected while serializing an object of type Lookup.

我该如何解决这个问题?

我使用以下代码进行序列化:

public static string Serialize(object obj)
{
    XmlSerializer ser = new XmlSerializer(obj.GetType());
    StringBuilder sb = new StringBuilder();
    StringWriter writer = new StringWriter(sb);
    ser.Serialize(writer, obj);
    return sb.ToString();
}

更新 课程的骨架:

[ActiveRecord(Lazy = true)] public class Lookup:ActiveRecordExtender,IComparable {     公共查找()     {     }

[Property]
public virtual string Title { set; get; } 

// creating relation
[HasMany(typeof(LookupItem), Cascade = ManyRelationCascadeEnum.All)]
public virtual IList Items { set; get; }

}

[ActiveRecord(Lazy = true)] 公共类LookupItem:ActiveRecordExtender {     public LookupItem()     {     }

//creating relation
[BelongsTo("Lookup_ID")]
public virtual Lookup ContainerLookup { set; get; }

[Property]
public virtual string Title { set; get; } 

[Property]
public virtual string Value { set; get; } 

[Property]
public virtual int SortOrder { set; get; }

}

请注意我使用Catle ActiveRecord作为我的ORM,请注意此问题与ActiveRecordBase的继承无关。因为此域中没有关系的其他类可以正常工作。

2 个答案:

答案 0 :(得分:1)

答案 1 :(得分:0)

根据博客文章及其评论here,如果假设不需要相关数据,则添加[XmlIgnore]可解决问题。