我想将XML元素映射到我的数据库表中(使用实体框架):
var xmlSerializer = new XmlSerializer(typeof(Participant), new XmlRootAttribute("participant"));
var participant = (Participant)xmlSerializer.Deserialize(new StringReader(content));
我有可以通过]访问的参与者表>
[XmlRoot("participant", Namespace = "")] public partial class Participant { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")] public Participant() { this.GroupParticipant = new HashSet<GroupParticipant>(); this.ParticipantAddress = new HashSet<ParticipantAddress>(); this.ParticipantPublisher = new HashSet<ParticipantPublisher>(); this.ParticipantJob = new HashSet<ParticipantJob>(); this.ParticipantProvider = new HashSet<ParticipantProvider>(); } [XmlElement("firstName")] public string FirstName { get; set; } [XmlElement("lastName")] public string LastName { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] //[XmlElement("address")] //[XmlElement("address")] //[XmlArray("HashSet<ParticipantAddress>"), XmlElement("address")] //[XmlArrayItem("ICollection<ParticipantAddress>")] //[XmlAttribute(DataType = "ICollection<ParticipantAddress>", AttributeName = "address")] [XmlElement("address", typeof(List<ParticipantAddress>))] public virtual ICollection<ParticipantAddress> ParticipantAddress { get; set; } }
ParticipantAddress是ICollection:
[Serializable] [XmlInclude(typeof(HashSet<ParticipantAddress>))] public partial class ParticipantAddress { public int ParticipantAddressId { get; set; } public int ParticipantId { get; set; } [XmlElement("city")] public string City { get; set; } [XmlElement("state")] public string State { get; set; } [XmlElement("zipCode")] public string ZipCode { get; set; } public virtual Participant Participant { get; set; } }
异常说:
{“出现错误,反映了类型'x.Participant'。”}
我内在的异常说:
{“无法序列化类型为'System.Collections.Generic.ICollection'1的成员'xParticipant.ParticipantAddress' ]',请参阅内部异常以了解更多详细信息。“}
我正在通过streamReader读取XML。
我尝试过
是否有其他方法可以解决此问题,或者与我的问题相关的任何示例,或者需要在代码中进行任何更改?
我想将XML元素映射到我的数据库表中(使用Entity Framework):var xmlSerializer = new XmlSerializer(typeof(Participant),new XmlRootAttribute(“ participant”))); var参与者=(...
ICollection不可序列化。-您可以使用DTO。-您可以更改集合类型(即使用List <>)和XML序列化属性,以避免循环引用和/或禁用延迟加载(即,通过Include方法使用急切加载),否则可能会序列化整个数据库。
由于virtual
属性,您遇到了这个问题。您尝试序列化一个具有对另一个类的引用的类,该类又具有对第一个类的引用,该类具有无限循环。
我创建了一个区域并将ICollection <>更改为List <>,因为
我在下面的文章中回答了此问题,以将[System.Xml.Serialization.XmlIgnore]添加到entity.tt模板中