在Fluent NHibernate中引用具有公式的实体

我有一个具有N:1父子关系的模式,该模式存储在另一个表中并由公式选择。 是否可以使用公式将此实体映射到父级?

 public class ParentEntity { public virtual int ParentId { get; set; } public virtual ChildEntity Child{ get; set; } } public class ParentMapping : ClassMap { public ParentMapping() { Table("ParentTable"); Id(x => x.ParentId).Column("ParentId").GeneratedBy.Assigned().Not.Nullable(); References(x => x.Child).Formula( @"( SELECT TOP 1 ChildTable.ChildId FROM ChildTable WHERE ChildTable.ParentId = ParentId )" ); } } 

此映射生成的SQL如下所示:

 SELECT this_.ParentId, this_.ChildEntity_id FROM ParentTable this_ 

这不是我想要的。

如何引用此子实体并在父表中使用从公式中选择ChildId的公式而不是ChildId

我不会以任何方式讨论这种方法的正确性,只是试着回答。 你想做什么: 应该工作。 我在测试场景中检查了公式的正确性。 所以,是的公式可以这样使用。

但是因为它不起作用,我会有点猜测。 让我们从我的测试用例中生成的SQL开始,这是有效的。

 SELECT this_.ParentId as ParentId3_0_ , (SELECT TOP 1 Child.ChildId FROM Child WHERE Child.ParentId = this_.ParentId) as formula1_0_ FROM Parent this_ 

可能的问题

我看到两个可能的问题

1.不同的子ID列名称

首先在您的代码段中:

 References(x => x.Child).Formula( @"( SELECT TOP 1 ChildTable.ChildId FROM ChildTable WHERE ChildTable.ParentId = ParentId )" 

是子主键的列名: ChildId在SQL片段中是ChildEntity_id

 SELECT this_.ParentId, this_.ChildEntity_id FROM ParentTable this_ 

2. SQL Snippet不匹配

其次,您提到(上面的SQL语句)是生成的。 但它更像是这种映射的陈述:

 References(x => x.Child).Column("ChildEntity_id") 

所以不可能有一些旧/其他映射,实际上使用?

总结我想说,这种映射方式正在发挥作用。 所以你在正确的轨道上,但魔鬼隐藏在细节中 ;)