问题
I have the following database table:
Settings
Key | Value
---------------|-------------------
SomeSetting | Foo
AnotherSetting | Bar
... | ...
And want to map this to the following object:
public class Settings
{
public virtual string SomeSetting { get; set; }
public virtual string AnotherSetting { get; set; }
}
How could I accomplish this using (Fluent) NHibernate?
回答1:
I would map the key/value pairs to a private IDictionary and expose the properties by accessing the dictionary. See Ayende's blog entry on map for creating the dictionary. Something like:
public class Settings
{
private IDictionary<string, string> _dict;
//initialize dictionary in constructor
public Settings()
{
_dict = new Dictionary<string, string> { {"SomeSetting", string.Empty} };
}
public virtual string SomeSetting
{
get { return _dict["SomeSetting"]; }
set { _dict["SomeSetting"] = value; }
}
// etc.
}
回答2:
Well an alternate would be to have two columns: Key,Value
map them into a column in the database and now write a repository class with properties will be responsible for querying the database on the key and getting the value. your repository model might resemble your current object model.
public class Settings
{
private readonly ISession _session;
public Settings(ISEssion session)
{
_session=session;
}
public Setting SomeSetting { get {return session.QueryOver<Setting>().SingleOrDefault(x.Key=="SomeSetting "} }
}
what do you think?
来源:https://stackoverflow.com/questions/7146577/fluent-nhibernate-map-complete-table-to-one-object