I have an object Topic which is a self-related hierarchy where the child Topics are defined as
public class Topic : Entity {
public ISet<Topic> ChildTopics { get; internal set; }
public Topic ParentTopic { get; set; }
...
}
I’m writing a form (MVC3) to produce a drop-down list (Html.DropDownListFor) of the first-level topics (theoretically this will eventually AJAX into a second drop-down for second-level topics), but when it goes to save, it produces the ever-popular “Cannot cast…” exception (see question title).
The usual cause of this is that you used List or Set instead of IList or ISet, but I am using ISet, and it specifically says it can’t cast to ISet.
The reason this is a set is because you wouldn’t want a Topic being a child of another Topic more than once. The table mapping create by Fluent NH automapping is correct with this override:
mapping.HasMany<Topic>(t => t.ChildTopics).AsSet().Inverse().KeyColumn("TopicId");
In my project, as of NHibernate 3.2.0.400, this error still occurs if I use
System.Collections.Generic.ISet<T>instead ofIesi.Collections.Generic.ISet<T>. Simply changing the references around is minimal work and solves the problem.