2017-11-11 326 views
0

引用可以說我有這個類NHibernate的映射:有額外的限制

public class LinkingTable 
{ 
    public int PrimaryKey { get; set; } 
    public int LinkFk { get; set; } 
    public string LinkTable { get; set; } 

    public OtherTable OtherTable { get; set; } 
} 

和其他一些類

public class OtherTable 
{ 
    public int PrimaryKey { get; set; } 
    ... other properties 
} 

映射看起來有點像這個

LinkingTableMap() : ClassMap<LinkingTable> 
{ 
    Id(x => x.PrimaryKey); 
    Map(x => x.LinkFK); 
    Map(x => x.LinkTable); 
    References(x => x.OtherTable, nameof(LinkingTable.LinkFk)); 
} 

OtherTableMap() : ClassMap<OtherTable> 
{ 
    Id(x => x.PrimaryKey); 
    ... other mappings 
} 

我想要將約束添加到LinkingTableMap中的OtherTable引用。類似於

References(x => x.OtherTable, nameof(LinkingTable.LinkFk)).Where(x => x.LinkTable == "OtherTable"); 

Where方法顯然不存在。我需要添加這個約束,因爲我可能有第三個表可能有重複的主鍵。 是這樣的可能嗎?

小編輯

約束爲常數,我不想引用另一列(這將不存在)

+0

提示的關鍵特性:確保所有你的模型的屬性和方法是'虛擬'的。 –

+0

過濾器是否適合您? https://weblogs.asp.net/ricardoperes/lesser-known-nhibernate-features-filters –

+0

@FelipeOriani你是對的。我忘了這篇文章的目的 – ZrSiO4

回答

0

好吧,我已經找到一種方法來做到這一點,似乎工作正常。

當映射參考實體屬性,我添加了一個公式來約束這樣的

References(x => x.OtherTable).Formula("(case when LinkTable = 'OtherTable' then LinkFk else 0 end)") 

導致SQL,看起來像這樣

select * 
from [LinkingTable] linkingTable 
left outer join [OtherTable] otherTable on (case when linkingTable.LinkTable = 'OtherTable' then linkingTable.LinkFk else 0 end)=otherTable.PrimaryKey