2009-02-05 41 views
3

是否有可能在兩個類之間沒有指定的映射(使用Criteria API)?NHibernate - 無需映射即可加入

我必須加入兩個類並從兩者中檢索數據,但我無法映射它們。我知道只有外鍵SomeID在第一類和主鍵ID在第二。

如何創建條件加入他們?沒有映射可能嗎?

請幫忙,我真的需要它,但我卡住了。 :/

PS

我知道 '任何' 的映射,但我有10個領域,如SomeID。創建任何僅用於創建連接的10個字段的映射都是過量的。 如果沒有其他決議我會做,但我不想。

回答

6

我不知道標準版,但在HQL你可以做這樣的:

select customer, order from Customer customer, Order order 
    where order.CustomerID = customer.Id 
    and customer.Id = 42 

結果集屆時將對象凡客將被重複多次的[]列表他所下的訂單數量(當然假設有多個訂單有一個客戶)。

請注意,如果沒有任何ordes,結果將爲空。

+0

Yeap。我正在通過Criteria使用它。 我正在尋找可能創造這樣的事情: 選擇客戶,訂單從客戶的客戶,訂貨訂單,用戶,用戶 其中order.SomeID_1 = customer.Id order.SomeID_2 = user.Id 我在設計時不知道SomeID_xxx包含的字段。 :/ – dariol 2009-02-05 11:48:09

1

如果你不想或者你不能在你的實體中定義關聯屬性(比如在支持動態加載插件的模塊化應用程序中),你仍然可以使用Fluent api創建「假」關聯。

查看果園源代碼「ContentItemAlteration」類。在Orchard中,ContentItem實體希望與存儲在不同表中的ContentPart記錄連接。每個ContentPart類型都由模塊提供,這意味着更改ContentItem的來源併爲每個新零件記錄添加關聯很困難(也可能不是最佳)。

這裏是確切的代碼,我從果園渠道獲得:

/// <summary> 
    /// Add a "fake" column to the automapping record so that the column can be 
    /// referenced when building joins accross content item record tables. 
    /// <typeparam name="TItemRecord">Either ContentItemRecord or ContentItemVersionRecord</typeparam> 
    /// <typeparam name="TPartRecord">A part record (deriving from TItemRecord)</typeparam> 
    /// </summary> 
    class Alteration<TItemRecord, TPartRecord> : IAlteration<TItemRecord> { 
     public void Override(AutoMapping<TItemRecord> mapping) { 

      // public TPartRecord TPartRecord {get;set;} 
      var name = typeof(TPartRecord).Name; 
      var dynamicMethod = new DynamicMethod(name, typeof(TPartRecord), null, typeof(TItemRecord)); 
      var syntheticMethod = new SyntheticMethodInfo(dynamicMethod, typeof(TItemRecord)); 
      var syntheticProperty = new SyntheticPropertyInfo(syntheticMethod); 

      // record => record.TPartRecord 
      var parameter = Expression.Parameter(typeof(TItemRecord), "record"); 
      var syntheticExpression = (Expression<Func<TItemRecord, TPartRecord>>)Expression.Lambda(
       typeof(Func<TItemRecord, TPartRecord>), 
       Expression.Property(parameter, syntheticProperty), 
       parameter); 

      mapping.References(syntheticExpression) 
       .Access.NoOp() 
       .Column("Id") 
       .ForeignKey("none") // prevent foreign key constraint from ContentItem(Version)Record to TPartRecord 
       .Unique() 
       .Not.Insert() 
       .Not.Update() 
       .Cascade.All(); 
     } 
    } 

此代碼只是增加了一個「部分」關聯ContentItem使您能夠使用連接在你的審覈規定。例如,如果您有一個名爲「ProductPart」的零件存儲在名爲「ProductPartRecord」的表中,那麼您可以將您的ContentItem加入僞造的屬性「ProductPartRecord」。

順便說一句,它似乎這種策略也可以應用到假關係的HasMany一側,但你必須定製我想的流利來源。