简体   繁体   中英

How to serialize two object with `one-to-many` relationship?

I have two classes: Lookup and LookupItem that Lookup has a member named Items that is a collection of LookupItem s. I'm not able to serialize Lookup or LookupItem . With the first I get error The type LookupItem was not expected. Use the XmlInclude or SoapInclude attribute to specify types that are not known statically. The type LookupItem was not expected. Use the XmlInclude or SoapInclude attribute to specify types that are not known statically. and with the second I got error A circular reference was detected while serializing an object of type Lookup. .

How can I solve this problem?

I use following code for serialization:

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();
}

UPDATE: skeleton of classes:

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

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

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

}

[ActiveRecord(Lazy = true)] public class 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; }

}

Please note I'm using Catle ActiveRecord as my ORM and please notice this problem is not related to inheritance from ActiveRecordBase . Because other classes in this domain that has no relations work properly.

I assume you want to serialize nested classes.

Have a look at similar post C# System.Xml.Serialization Self-nested elements

http://www.codeproject.com/KB/XML/Serializing_Nested_XML.aspx

根据博客文章,其意见在这里 ,如果假定没有必要有关数据显示,添加[XmlIgnore]解决了这个问题。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM