Brian
Brian

Reputation: 951

Fluent Nhibernate Multi-Level reference

I have a three generation class structure that I am attempting to ORM-ify using Fluent Nhibernate. To summarize the classes they look as such...

public class Highest{
  public virtual Guid Id{
    get;
    set;
  }

  public virtual IList<Medium> Children{
    get;
    set;
  }
}

public class Medium{
  public virtual int Index{
    get;
    set;
  }

  public virtual Highest Parent{
    get;
    set;
  }

  public virtual IList<Lowest> Children{
    get;
    set;
  }
}

public class Lowest{
  public virtual MyEnum LowType{
    get;
    set;
  }

  public virtual Medium Parent{
    get;
    set;
  }
}

I have attempted a number of tries to create the appropriate Maps using a simple Id for the highest level and composite Id for both the Medium and lowest levels. But all my strategies have failed for creating a compositeid for the lowest to the Medium since (I presume) it in turn uses a CompositeId from itself to Highest.

The Question! How should the maps be designed such that I am certain that when I load a Highest class all of Medium and Lower relationships will also be created, including the Parent/Children relationships.

Thanks!

Upvotes: 0

Views: 75

Answers (1)

Firo
Firo

Reputation: 30813

the mapping you requested

public class HighestMap : ClassMap<Highest>
{
    public HighestMap()
    {
        Id(x => x.Id).GeneratedBy.GuidComb();

        HasMany(x => x.Children)
            .KeyColumn("parent_id");
    }
}

public class MediumMap : ClassMap<Medium>
{
    public MediumMap()
    {
        CompositeId()
            .KeyReference(x => x.Parent, "parent_id")
            .KeyProperty(x => x.Index, "indexColumn");

        HasMany(x => x.Children)
            .KeyColumns.Add("medium_id", "indexColumn")
            .Component(c =>
            {
                c.ParentReference(x => x.Parent);
                c.Map(x => x.LowType);
            });
    }
}

However you said you want to load all in one go then it might be worth sacrificing queryability for performance. The following code will save the Medium.Children collection as a string in the database and is only queryable with equal and unequal session.Query<Medium>().Where(x => x.Children == myCollection);

public class Medium
{
    public virtual Highest Parent { get; set; }

    public virtual ICollection<MyEnum> Children { get; set; }
}

public class HighestMap : ClassMap<Highest>
{
    public HighestMap()
    {
        Id(x => x.Id).GeneratedBy.GuidComb();

        HasMany(x => x.Children)
            .KeyColumn("parent_id")
            .AsList(i => i.Column("indexColumn"))
            .Component(c => 
            {
                c.ParentReference(x => x.Parent);

                // remove Index property and use Highest.Children.IndexOf(medium)

                c.Map(x => x.Children).CustomType<EnumCollectionAsStringUserType<MyEnum>>();
            });
    }
}

[Serializable]
public class EnumCollectionAsStringUserType<TEnum> : IUserType
{
    public object NullSafeGet(IDataReader rs, string[] names, object owner)
    {
        var value = (string)NHibernateUtil.String.Get(rs, names[0]);

        if (string.IsNullOrEmpty(value))
            return new List<TEnum>();

        return value.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(Parse).ToList();
    }

    private static TEnum Parse(string arg)
    {
        return (TEnum)Enum.Parse(typeof(TEnum), arg);
    }

    public void NullSafeSet(IDbCommand cmd, object value, int index)
    {
        var collection = (IEnumerable<TEnum>)value;
        NHibernateUtil.String.Set(cmd, string.Join(",", collection), index);
    }

    public Type ReturnedType { get { return typeof(ICollection<TEnum>); } }

    public SqlType[] SqlTypes { get { return new[] { SqlTypeFactory.GetString(255) }; } }

    public object DeepCopy(object value)
    {
        return new List<TEnum>((IEnumerable<TEnum>)value);
    }

    bool IUserType.Equals(object x, object y)
    {
        return ((IEnumerable<TEnum>)x).SequenceEqual((IEnumerable<TEnum>)y);
    }

    int IUserType.GetHashCode(object x)
    {
        return ((IEnumerable<TEnum>)x).Aggregate(0, (a, v) => a << 8 + v.GetHashCode());
    }

    public object Assemble(object cached, object owner)
    {
        return DeepCopy(cached);
    }

    public object Disassemble(object value)
    {
        return DeepCopy(value);
    }

    public bool IsMutable { get { return true; } }

    public object Replace(object original, object target, object owner)
    {
        return original;
    }
}

Upvotes: 2

Related Questions