Search code examples
c#nhibernatefluent-nhibernatenhibernate-mappingfluent-nhibernate-mapping

Fluent Nhibernate List<string> mapping


I have a simple class with a IList<string> property. How to map this property in Fluent Nhibernate ?

[Serializable]
public class ExportTask
{
    private IList<string> _csvExportList = new List<string>();

    public ExportTask()
    {}

    public virtual IList<string> CsvExportList
    {
        get { return _csvExportList; }
        set { _csvExportList = value; }
    }
}

public class ExportTaskMap : SubclassMap<ExportTask>
{
    public ExportTaskMap()
    {           
        HasMany(x => x.CsvExportList)
               .Element("CsvExportList")
               .Cascade
               .AllDeleteOrphan();
    }
}

Following error occurs:

Initializing -failed to lazily initialize a collection of role: MyApp.Tasks.ExportTask.CsvExportList, no session or session was closed

When calling addrange on the collection:

var exportList = new List<string>()
                     {
                        {"item1"},
                        {"item2"}
                      };

CsvExportList.AddRange(exportList);

Solution

  • It truns out we can use AsList mapping with a column for the list index and allworks great. I wonder why there are no answers out there for this simple usecase. Hope it helps out someone.

    public class ExportTaskMap : SubclassMap<ExportTask>
    {
      public ExportTaskMap()
      {           
         HasMany(x => x.CsvExportList)
               .Element(@"CsvProperty")
               .KeyColumn(@"ExportTask_id")
               .Table(@"CsvExportProperties")
               .AsList(x => x.Column(@"CsvPropertyListIndex"))
               .Not.LazyLoad();
      }
    }
    

    And the mapped table will look like the following in the database.

    enter image description here