[英]Fluent NHibernate - How to map to table which has reference to a lookup table
[英]How to map NHibernate variable table reference?
有一个名为ChildTable
的表,其中包含2列SourceTable
和SourceId
以及其他一些表ParentTable1
, ParentTable2
等。
当SourceTable
具有与该表关联的值时, SourceId
的Id可用于连接到父表(1 - > ParentTable1
- > ParentTable2
)。 例如,要获取与ParentTable1
行关联的所有ChildTable
行,可以使用此查询来实现:
select *
from ChildTable ct
join ParentTable1 pt1
on ct.SourceTable = 1 and ct.SourceId = pt1.Id
我想将这两个ChildTable
列映射为每个父表的1个属性:Parent1,Parent2,...因此其中1个不为null,其余的父属性为null:
public class ChildClass
{
public Parent1Class Parent1 { get; set; }
public Parent2Class Parent2 { get; set; }
public Parent3Class Parent3 { get; set; }
.
.
.
}
问题是:如何为这种情况编写映射(如果可能,按代码映射)?
注意:这是用于映射现有表,重构表模式还不是解决方案(但欢迎提出建议)。
更新
出于查询的目的,似乎足以将ChildClass属性Parent1映射为:
ManyToOne(property => property.Parent1, map => map.Formula("(select pt1.Id from dbo.ParentTable1 pt1 where SourceTable = 1 and pt1.Id = SourceId)"));
和Parent1Class的Children集合:
mapper.Where("SourceTable = 1");
对于更新/插入,可能使用访问器可以实现,稍后将发布更新。
你为什么不使用Any
?
类:
public class ChildClass
{
public virtual ParentBase Parent { get; set; }
// beware of proxies when casting... this may not work like this
public Parent1Class Parent1 { get { return Parent as Parent1Class; } }
public Parent2Class Parent2 { get { return Parent as Parent2Class; } }
.
.
.
}
制图:
Any(x => x.Parent, typeof(int), m =>
{
m.IdType<int>();
m.MetaType<int>();
m.MetaValue(1, typeof(Parent1));
m.MetaValue(2, typeof(Parent2));
m.Columns(
id => id.Name("SourceId"),
classRef => classRef.Name("SourceTable"));
});
还有many-to-any
对任何类型,它将任何类型的集合映射到关系表中。
在查询中使用它时,可以检查.class
,或使用子查询:
HQL:
select *
from ChildTable ct join Parent
where pt1.class = Parent1
要么
select *
from ChildTable ct
Where ct.Parent in (from Parant2 p where p.Property = 'Hugo')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.