How do I map the collection of Parts using a convention?
public class Part
{
public virtual int Id { get; set; }
public virtual string Name { get; set; }
}
public class Car
{
private readonly List<Part> _parts = new List<Part>();
public virtual int Id { get; set; }
public virtual IList<Part> Parts
{
get { return _parts.AsReadOnly(); }
}
}
I have tried this convention but it always expects the field name without an underscore prefix:
public class HasManyConvention : IHasManyConvention
{
public void Apply(IOneToManyCollectionInstance instance)
{
instance.Access.ReadOnlyPropertyThroughCamelCaseField(CamelCasePrefix.Underscore);
}
}
I’ve tried it with the 1.2.0.694 and 2.0.0.698 builds with the same result:
"Could not find field 'parts' in class 'TestFluentNHibernate.Car'"
First of all, your _parts member can’t be read-only. NHibernate needs write access to the member to set the value/reference. To return a truly read-only collection through the Parts property you have to return a System.Collections.ObjectModel.ReadOnlyCollection. This also “removes” all the methods found in the read/write collection types that are still there if you just return f.ex. list.AsReadOnly(). A read-only list returned in this way still have .Add() method and others to edit the collection, but they will cause a runtime exception so returning a ReadOnlyCollection to begin with is a great for preventing this possibility.
A lot of people seem to like returning an IEnumerable which is also read-only, but it can be cast to a List or other read/write collection type and changed that way.
You have to implement AddPart and RemovePart methods to allow external code to add and remove items to the read-only collection.
Your convention looks correct, I’m using the exact same syntax with 1.2.0.694 successfully, my convention:
Example class: