3

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.

oleksii
  • 35,458
  • 16
  • 93
  • 163
Alexandr
  • 5,460
  • 4
  • 40
  • 70

2 Answers2

1

You should use the <many-to-one> in XML, or it's equivalent in the other mapping systems, just like you would for any other class.

Oskar Berggren
  • 5,583
  • 1
  • 19
  • 36
1

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");
  }
 }
Radim Köhler
  • 122,561
  • 47
  • 239
  • 335