NHibernate映射:带有附加约束的引用

时间:2017-11-11 00:17:43

标签: nhibernate fluent-nhibernate-mapping

让我说我有这个班级

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方法显然不存在。我需要添加此约束,因为我可能有第三个表可能有重复的主键。 这样的事情可能吗?

小编辑

约束是常数,我不想引用另一列(不存在)

1 个答案:

答案 0 :(得分: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