Wednesday, August 17, 2011

Mapping a Dictionary in NHibernate

For one of my projects, our end-users went crazy and asked for a dynamic fields feature which allows them to add and remove some extra fields on every entity. This is actually quite easy to implement with NHibernate.

Let’s first have a look at the entity(this is a simplified version):

public class File
public virtual int Id { get; set; }
public virtual string Name { get; set; }
public virtual IDictionary<string, string> Attributes { get; set; }

And the corresponding mapping file (didn’t had time to look at the code mapping yet):

<class name="File" table="Files">
<id name="Id">
<generator class="native"/>
<property name="Name"/>

<map name="Attributes" table="FileAttributes">
<key column="FileId"/>
<index column="AttributeName" type="System.String"/>
<element column="Attributevalue" type="System.String"/>

And that’s all you need to do. This will create  2 tables, one table(Files) with the File properties and one table(FileAttributes) with the extra values.

Anyone who knows how to do the same thing with Entity Framework?

1 comment:

Mike said...

Great! Thanks! Just what I was looking for. Works like a charm!