2012-03-29 51 views
1

假設我有兩個表:加入表映射與逆FK

表MY_ENTITY

ID: PK 
OTHER_ID: FK to table OTHER 

表中的其他

ID: PK 
COL: The column I want 

我的實體是這樣的:

class MyEntity : Entity 
{ 
    public virtual Column { get; set; } 
} 

我的自動映射覆蓋看起來像這樣:

mapping.IgnoreProperty(x => x.Column); 
mapping.Join("OTHER", x => x.KeyColumn("ID").Optional() 
          .Map(y => y.Column, "COL"); 

這工作正常,執行沒有問題,但連接是錯誤的。

它創建一條SQL語句,將MY_ENTITY的PK連接到表OTHER中的KeyColumn中指定的列。沿着線的東西:

select ... from MY_ENTITY e left outer join OTHER o on e.ID = o.ID 

不過,我需要的連接是這樣的:

select ... from MY_ENTITY e left outer join OTHER o on e.OTHER_ID = o.ID 

如何實現這一目標?

回答

1

你就必須將OtherId屬性添加到MyEntity(它不必是公共的,它只是用於映射)和連接鍵映射使用PropertyRef(這是由代碼映射方法名;它是property-ref在XML中,您必須查看Fluent)

或者,將Other作爲一個實體並使用ReferenceMyEntity。你可以級聯所有,所以它與MyEntity一起被持續/刪除。

然後,就項目所引用的屬性(它不會myEntity所映射):

class MyEntity 
{ 
    public virtual PropertyType Property 
    { 
     get 
     { 
      EnsureOther(); 
      return Other.Property; 
     } 
     set 
     { 
      EnsureOther(); 
      other.Property = value; 
     } 
    } 

    void EnsureOther() 
    { 
     if (Other == null) 
      Other = new Other(); 
    } 

    public virtual Other { get; set; } 
} 

class Other 
{ 
    public virtual PropertyType Property { get; set; } 
} 
+0

謝謝!該投影是一個不錯的主意,它直接解決了我的下一個問題:「如何正確堅持一個具有PK連接表的實體」? :-) – 2012-03-29 11:50:05

1

也許你應該使用Referencesmany-to-one)映射來代替。

References(x => x.Other, "OTHER_ID") 
    .Fetch.Join() 
+0

是的,Diego就是這麼建議的。 – 2012-03-29 11:56:39

+0

是的,當我完成這個時,我看到了一個答案彈出。 – 2012-03-29 11:58:09