我有一个架构N:1
父子关系存储在另一个表中并通过公式选择。是否可以使用公式将该实体映射到父实体?
public class ParentEntity {
public virtual int ParentId { get; set; }
public virtual ChildEntity Child{ get; set; }
}
public class ParentMapping : ClassMap<ParentEntity> {
public ParentMapping() {
Table("ParentTable");
Id(x => x.ParentId).Column("ParentId").GeneratedBy.Assigned().Not.Nullable();
References<ChildEntity>(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
从一个公式?
无论如何,我不会讨论这种方法的正确性,只是尝试回答。你正在尝试做什么:should工作。我已经在测试场景中检查了公式的正确性。所以,是的,公式可以完全这样使用。
但因为它不起作用,我有点猜测。让我们从我的测试用例中生成的 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、Child ID列名不同
首先在你的代码片段中:
References<ChildEntity>(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 片段不匹配
其次,您提到(上面的 SQL 语句)是生成的。但它更像是这个映射的声明:
References<ChildEntity>(x => x.Child).Column("ChildEntity_id")
那么不可能有一些实际上已使用的旧/其他映射吗?
概括
我想说,这种映射方式是有效的。所以你走在正确的轨道上,但是魔鬼隐藏在细节中 ;)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)