Search code examples
.netnhibernatefluent-nhibernatenhibernate-mappingfluent-nhibernate-mapping

Trying to map entity with type like it has as a member


I am new to nHibernate, here is my code

public abstract class DEField : EntityWithSerializableId
{
    public virtual Boolean IsVisibilityDepended { get; set; }
    public virtual DEField VisibilityField { get; set; }
    public virtual String VisibilityExpression { get; set; }  
}

I am trying to understand how to map entity that has the same type in its members (DEField). This entity could be nullable.


Solution

  • Mapping in this case (property type is same as the Entity) is a simple/standard reference mapping. You can take a look here for more details: Fluent mapping

    References / many-to-one:

     ...
     References(x => x.VisibilityField);
    

    And that's it. In cases like this, usually Parent Child relation could be indicated. So not only your DEField references itself as VisibilityField, but it also should know (from the point of view of the VisibilityField) who is referencing it. The 1) Parent reference and 2) Children collection:

    public abstract class DEField : EntityWithSerializableId
    {
        public virtual Boolean IsVisibilityDepended { get; set; }
        public virtual String VisibilityExpression { get; set; }  
    
        public virtual DEField VisibilityField { get; set; } // Parent
        public virtual IList<DEField> ChildFields { get; set; } // Children
    }
    

    And a bit more complex mapping example then could look like this:

     public class DEFieldMap : ClassMap<DEField>
     {
      public DEFieldMap()
      {
         Table("DEFieldTable");
         LazyLoad();
         Id(x => x.Id)
          .Column("Id")
          .Not.Nullable()    
          .GeneratedBy.Identity();
         Map(x => x.IsVisibilityDepended );
         Map(x => x.VisibilityExpression);
         References(x => x.VisibilityField)
          .Class<DEField>()
          .Access.Property()
          .Cascade.None()
          .LazyLoad()
          .Column("ParentId");
         HasMany<DEField>(x => x.ChildFields) // Children     
          .Access.Property()
          .AsBag()
          .Cascade.None()
          .LazyLoad()
          .Inverse()
          .KeyColumn("ParentId");
      }
     }