<Map> = IDictionary

一世执手 提交于 2019-12-12 05:39:36

问题


I have 3 entities: class User {id,name...} class UserUrl {id,user_id,url,url_type_id} class UrlType {id,name} My mapping:
<class name="User" table="Users" lazy="false">
  <id name="id" type="Int32" column="id">
    <generator class="identity" />
  </id>
  <property name="name" column="name" type="String"/>
  <map name="Urls" table="UserUrl">
     <key column="user_id"></key>
     <index-many-to-many class="UrlType" column="url_type_id"/>
     <one-to-many class="UserUrl"/>
   </map>
</class>
<class name="UserUrl" table="UserUrl">
   <id name="id" type="Int32" column="id">
    <generator class="identity"/>
   </id>
   <property name="user_id" column="user_id" type="Int32"/>
   <many-to-one name="UrlType" column="url_type_id" class="UrlType"/>
   <property name="Url" column="url" type="String" not-null="true"/>
</class> >
So User.Urls is IDictionary<UrlType,UserUrl>. But I want to get Dictionary<string,UserUrl>, where string key is UrlType.name. Does anybody know how to do this?


回答1:


NHibernate will give you an interface for collections, in this case IDictionary as its implementation will involve proxies and caching and you won't want to know the details. So you won't get a Dictionary.

My question would be why do you want a Dictionary, you access all the data via the IDictionary interface what extra functionality would a concrete class give?




回答2:


I find out desition.
Mapping:

<class name="User" table="Users" lazy="false">
  <id name="id" type="Int32" column="id">
    <generator class="identity" />
  </id>
  <property name="name" column="name" type="String"/>
  <map name="Urls" lazy="true" cascade="all-delete-orphan" inverse="true">
     <key column="user_id"></key>
     <index column="im_type_id" type="Int32"/>
     <one-to-many class="UserUrl"/>
   </map>
</class>
<class name="UserUrl" table="UserUrl">
   <id name="id" type="Int32" column="id">
    <generator class="identity"/>
   </id>
   <property name="user_id" column="user_id" type="Int32"/>
   <property name="UrlType" column="url_type_id" type="Int32" not-null="true" />
   <property name="Url" column="url" type="String" not-null="true"/>
</class>

Code:

public sealed class UrlType
{
  private const string _Facebook = "Facebook";  
  private const string _Myspace = "Myspace";   
  private const string _Youtube = "Youtube";

  public static readonly int Facebook;
  public static readonly int Myspace;
  public static readonly int Youtube;
  static UrlType()
  {
     Facebook = FindByName(_Facebook).Id;
     Myspace = FindByName(_Myspace).Id;
     Youtube = FindByName(_Youtube).Id;
  }
}

Use:

User curUser = FindById(2);  
string facebookUrl = curUser.Urls[UrlType.Facebook].Url; 

But It is spend more time to get ids of Urls types from DB



来源:https://stackoverflow.com/questions/1232303/map-idictionary

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