map table to itself in Parent-Child relationship Fluent Nhibernate
I have situation where I am mapping table's columns to the primary key of same table. The table looks like this
---+-------+---------
ID Name ParentId
---+-------+---------
1 Parent1 0
2 Child 1 1
3 Child 2 1
4 Parent2 0
5 Child 3 4
I have created a following Model and Fluent NHibernate mapping class
//Model.LocationType.cs
public class LocationType
{
public virtual long Id { get; set; }
public virtual string ShortName { get; set; }
public virtual string Description { get; set; }
public virtual IList<LocationType> ParentId { get; set; }
}
and
//Mapping.LocationTypeMap.cs
public class LocationTypeMap : ClassMap<LocationType>
{
public LocationTypeMap()
{
Table("SET_LOC_TYPE");
Id(x => x.Id).Column("LOC_TYPE_ID").GeneratedBy.Assigned();
Map(x => x.ShortName, "SHORT_NAME").Length(15).Not.Nullable();
Map(x => x.Description, "LOC_DESC").Length(50).Not.Nullable();
References(x => x.ParentId).Column("PARENT_LOC_TYPE_ID").Cascade.SaveUpdate();
}
}
but I am receiving follow error message when i execute my code:
Unable to cast object of type 'SmartHRMS.Core.Domain.Model.LocationType' to type 'System.Collections.Generic.IList`1[SmartHRMS.Core.Domain.Model.LocationType]'.
Edit 1: Instead of using i tried
HasMany(x => x.ParentIds).KeyColumn("PARENT_LOC_TYPE_ID");
Although it worked and solved the casting problem that I mentioned above but the result I am gettting is the reverse of what i need.开发者_运维问答 In parent's LocationType objects, it lists all childs in IList, so for above example the result will be:
-----+----------+------
ID Name ParentId
-----+----------+------
1 Parent1 IList<Child1, Child2>
2 Child 2 IList<Empty>
3 .... same
4 Parent2 IList<Child3>
5 Child 3 IList<Empty>
Seems like you should use HasMany
in your mapping instead of References
.
精彩评论