(Fluent) NHibernate: Map complete table to one object

橙三吉。 提交于 2019-12-24 07:25:26

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!