How to map IDictionary<string, object> in Fluent NHibernate?
Posted
by user298221
on Stack Overflow
See other posts from Stack Overflow
or by user298221
Published on 2010-03-21T00:52:40Z
Indexed on
2010/03/21
1:01 UTC
Read the original article
Hit count: 530
I am looking to persist user preferences into a collection of name value pairs, where the value may be an int, bool, or string.
There are a few ways to skin this cat, but the most convenient method I can think of is something like this:
public class User
{
public virtual IDictionary<string, object> Preferences { get; set; }
}
with its usage as:
user.Preferences["preference1"] = "some value";
user.Preferences["preference2"] = 10;
user.Preferences["preference3"] = true;
var pref = (int)user.Preferences["preference2"];
I'm not sure how to map this in Fluent NHibernate, though I do think it is possible.
Generally, you would map a simpler Dictionary<string, string> as:
HasMany(x => x.Preferences)
.Table("Preferences")
.AsMap("preferenceName")
.Element("preferenceValue");
But with a type of 'object', NHibernate doesn't know how to deal with it. I imagine a custom UserType could be created that breaks an 'object' down to a string representing its Type and a string representing the value. We would have a table that looks kind of like this:
Table Preferences
userId (int)
preferenceName (varchar)
preferenceValue (varchar)
preferenceValueType (varchar)
and the hibernate mapping would like this:
<map name="Preferences" table="Preferences">
<key column="userId"></key>
<index column="preferenceName" type="String" />
<element type="ObjectAsStringUserType, Assembly">
<column name="preferenceValue" />
<column name="preferenceValueType"/>
</element>
</map>
I'm not sure how you would map this in Fluent NHibernate.
Maybe there's a better way to do this, or maybe I should just suck it up and use IDictionary<string, string>. Any ideas?
© Stack Overflow or respective owner