Friday, February 3, 2012

Mapping-by-Code - List, Array, IdBag

Time to complete the subject of collection mappings - there are some features unique for lists and idbags that need to be mentioned. I'll skip all the options that are common with set and bag and refer to its own post.

List is an explicitly ordered collection. It has an additional option in the mapping for the index column that keeps the ordering, with the standard Column options mapping inside.

List(x => x.Districts, c =>
{
c.Index(idx =>
{
idx.Base(1);
idx.Column("indexColumnName");
// or
idx.Column(ic =>
{
ic.Name("indexColumnName");
// etc...
});
});
});

There are two other rarely used ordered collections in NHibernate - arrays and primitive arrays. Both are not supported in mapping-by-code. But I don't think it's a big deal.

Another collection type is IdBag. It is generally a bag enriched with additional identity column - useful for many-to-many intermediate tables, when we don't want to have composite primary key there. The only new option in the mapping is Id method, with several options available:

IdBag(x => x.Collection, c =>
{
c.Id(i =>
{
i.Column("idColumn");
i.Generator(Generators.Native);
i.Length(100);
i.Type(new Int32Type());
});
}, r => r.ManyToMany());

Fluent NHibernate's equivalents

As we already know, FNH defines collection mappings as a part of relation mapping chain. I'll skip all the options already covered in the Bag/Set post.

List is mapped using AsList method. There is a possibility to set index column name and type - other DDL options, as well as base attribute are missing.

HasMany(x => x.Users)
.AsList(idx => idx.Column("indexColumnName").Type<int>())

Array is also supported, contrary to mapping-by-code. It has similiar possibilities to the list mapping, the only difference is that we can define index column name by lambda parameter, but it's used only if we don't specify it in the second parameter explicitly.

HasMany(x => x.Users)
.AsArray(x => x.Name, idx => idx.Column("indexColumnName").Type<string>())

Primitive arrays and idbags are not supported.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.