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);
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.
Would be helpful to see the error you get, but one thing seems to be obvious: you are missing setter of the IList<string> CsvExportList
. So, mapping should target the field
HasMany<string>(Reveal.Property<string>("_csvExportList"))
Check these how to handle field mapping:
Or change your IList<string>
to have at least protected setter (I personally would go this way) and remove the readonly setting.
private IList<string> _csvExportList;
public virtual IList<string> CsvExportList
{
get { return _csvExportList ?? (_csvExportList = new List<string>(); }
protected set { _csvExportList = value; }
}
These are hints, the exception or error you get could tell us more
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.