Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NHibernate: How do I XmlSerialize an ISet<T>?

Given:

  • I'm trying to create a REST API using ASP.NET MVC.
  • I'm using NHibernate in my data access layer.

Problem:

  • I'm can't XmlSerialize ISet properties.

I get errors like the following:

Cannot serialize member [namespace].[entity].[property] of type Iesi.Collections.Generic.ISet`1[[namespace].[entity], [assembly], Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]] because it is an interface.

  • I'll freely admit: I'm very new to NHibernate.
    • So I don't know what my options are.
  • I believe that I need to use a set as opposed to a bag because my collections contain unique items.
  • When I converted the ISet properties to HashedTable properties (i.e. a concrete class), I got errors like the following:

You must implement a default accessor on Iesi.Collections.Generic.HashedSet`1[[namespace].[entity], [assembly], Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]] because it inherits from ICollection.

My questions:

  • What should I do to remedy this situation?
    • Should I implement default accessors in all of my entity classes?
      • If so, is there a recommended pattern for doing so?

As a sidenote, I tried Googling for help.
- I don't think this is a new problem.

like image 825
Jim G. Avatar asked Dec 24 '09 15:12

Jim G.


3 Answers

NHibernate serialization has been treated a lot on stackoverflow. See:

  • C# Castle ActiveRecord: How to elegantly (XML) serialize ActiveRecord objects?
  • How do I serialize all properties of an NHibernate-mapped object?
  • NHibernate and WCF Serialization(Unidirectional)
  • JSON.NET and nHibernate Lazy Loading of Collections
  • Which .NET JSON serializers can deal with NHibernate proxy objects?
  • DTOs vs Serializing Persisted Entities
  • Returning NHibernate mapping classes from WCF services

Bottom line: use DTOs.

like image 190
Mauricio Scheffer Avatar answered Nov 19 '22 23:11

Mauricio Scheffer


Try using the DataContractSerializer instead. It's more restrictive, but will serialize more.

Dan Rigsby explains the difference between XMLSerializer and DataContractSerializer

Here's an example from one of my posts on stackoverflow:

public XDocument GetProductXML(Product product)
    {
        var serializer = new DataContractSerializer(typeof(Product));
        var document = new XDocument();

        using (var writer = document.CreateWriter())
        {
            serializer.WriteObject(writer, product);
            writer.Close();
        }

        return document;
    }
like image 31
autonomatt Avatar answered Nov 20 '22 00:11

autonomatt


You can never XML Serialize an interface - only a concrete class that implements the interface.

like image 1
John Saunders Avatar answered Nov 20 '22 01:11

John Saunders