0
votes

We are using custom collection classes to hold our entity collections but I am having a problem mapping the collection properties for Fluent NHibernate. I have read all the posts on this site on a similar theme but none seem to address our particular situation.

A collection class typical of our model is:

public class ElementList : IEnumerable<Element>
{
    private List<Element> list = new List<Element>();
    public ElementList(IEnumerable<Element> elements)
    {
        this.list.AddRange(elements);
    }
    protected ElementList() {}
    protected List<Element> InternalList
    {
        get { return this.list; }
        set { this.list = value; }
    }
    public IEnumerator<Element> GetEnumerator()
    {
        return this.list.GetEnumerator();
    }
    IEnumerator IEnumerable.GetEnumerator()
    {
        return this.GetEnumerator();
    }
}

This is a property on the parent object:

public class Paragraph
{
    private ElementList elements;
    public Paragraph(params Element[] elements)
    {
        this.elements = new ElementList(elements.ToList());
    }
    protected Paragraph()
    {
    }
    public virtual int Id { get; protected set; }
    public virtual ElementList Elements
    {
        get { return this.elements; }
        protected set { this.elements = value; }
    }
}

I have tried mapping this as follows:

public ParagraphMap()
{
    this.Id(x => x.Id);
    Component(
            x => x.Elements,
            m => m.HasMany<Element>(Reveal.Member<ElementList>("InternalList")).AsSet().KeyColumn("ParagraphId"));
}

This is fine when I create my repository and the tables are created as I'd expect. The problem is when I try and add a Paragraph object. The following code throws an InvalidCastException because I am unable to cast an object of type 'NHibernate.Collection.Generic.PersistentGenericSet[Element]' to type 'System.Collections.Generic.List[Element]':

var elements = new Element[] { new Element(), new Element() };
var paragraph = new Paragraph(elements);

using (var unitOfWork = this.repository.Begin())
{
    this.repository.Add(paragraph);
}

What am I doing wrong?

I have noted a lot of posts saying it is perhaps better not to use custom collections but doing so is a standard on our project so I would like to persevere and get it working.

1

1 Answers

1
votes

I think your custom collection also needs to implement either IList<Element> or ICollection<Element>. Probably ICollection as it is a set.