簡體   English   中英

用NHibernate進行類映射

[英]Class mapping with NHibernate

我有一個普通的數據庫表(名為DBFoo):

| PropertyA | PropertyB| PropertyC | PropertyD | PropertyE |

PropertyA,PropertyB和PropertyC是鍵的一部分。

為此,在我的程序中,我具有以下類結構:

public class Foo
{
   public virtual SubFoo SubFoo { get; set; }
   public virtual string PropertyC { get; set; }
   public virtual string PropertyD { get; set; }
   public virtual string PropertyE { get; set; }
}

public class SubFoo
{
   public virtual string PropertyA { get; set; }
   public virtual string PropertyB { get; set; }
}

現在,我正在嘗試創建映射文件:

...
<class name="Foo" table="DBFoo">
   <composite-id>
      // here I Need to define the mapping for the SubFoo properties PropertyA and PropertyB
      <key-property name="PropertyC" column="PropertyC"/>
   </composite-id>
   <property name="PropertyD" column="PropertyD"/>
   <property name="PropertyE" column="PropertyE"/>
</class>
....

有人知道如何為PropertyA和PropertyB定義鍵屬性嗎?

預先感謝您的幫助

可能不是一個好主意,但是您可以嘗試生成一個FooIdentifier類來裝飾SubFoo類,以提供對PropertyAPropertyBPropertyC直接訪問。

public class FooIdentifier
{
    private SubFoo InnerSubFoo { get; set; }
    public FooIdentifier(SubFoo subFoo, string propertyC)
    {
        this.InnerSubFoo = subFoo
        this.PropertyC = propertyC;
    }   

    public virtual string PropertyA 
    { 
        get 
        { 
            return SubFoo.PropertyA; 
        } 
        set 
        {
            SubFoo.PropertyA = value; 
        }
    }

    public virtual string PropertyB
    {
        get
        {
            return SubFoo.PropertyB; 
        }
        set 
        {
            SubFoo.PropertyB = value;
        }
    }

    public virtual string PropertyC { get; set; }
}

然后,映射文件可能類似於:

<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
  <class name="Foo" table="Foo" lazy="true" >
    <composite-id name="FooIdentifier" class="FooIdentifier">
      <key-property name="PropertyA" column="PropertyA" />
      <key-property name="PropertyB" column="PropertyB" />
      <key-property name="PropertyC" column="PropertyB" />
    </composite-id>
    <property name="PropertyD" column="PropertyD" type="String" />
    <property name="PropertyE" column="PropertyE" type="String" />
  </class>
</hibernate-mapping>

正如HuorSwords提到的那樣,您可以為表定義一個復合鍵,為此,您必須創建一個復合鍵類,其中包含屬性並覆蓋hashkey和equals方法...

請閱讀此博客,以獲取有關應如何實施的更多詳細信息。

但是我強烈建議您不要使用組合鍵,因為通常會出現一些問題。 另外,建議在每個表中或多或少具有代理鍵 ,並在需要時具有輔助鍵/外鍵。

這也使nhibernate映射更加容易!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM