NHibernate 映射:具有附加约束的引用
NHibernate mapping: references with additional constraint
假设我有这个class
public class LinkingTable
{
public int PrimaryKey { get; set; }
public int LinkFk { get; set; }
public string LinkTable { get; set; }
public OtherTable OtherTable { get; set; }
}
和其他一些 class
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 方法显然不存在。我需要添加此约束,因为我可能有第三个 table 可能具有重复的主键。
这样的事情可能吗?
小编辑
约束是常量,我不想引用另一列(它不会存在)
好的,我找到了一种看起来还不错的方法。
在将引用映射到实体 属性 时,我添加了一个公式来约束键 属性,就像这样
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
假设我有这个class
public class LinkingTable
{
public int PrimaryKey { get; set; }
public int LinkFk { get; set; }
public string LinkTable { get; set; }
public OtherTable OtherTable { get; set; }
}
和其他一些 class
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 方法显然不存在。我需要添加此约束,因为我可能有第三个 table 可能具有重复的主键。 这样的事情可能吗?
小编辑
约束是常量,我不想引用另一列(它不会存在)
好的,我找到了一种看起来还不错的方法。
在将引用映射到实体 属性 时,我添加了一个公式来约束键 属性,就像这样
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