繁体   English   中英

如何映射NHibernate变量表引用?

[英]How to map NHibernate variable table reference?

有一个名为ChildTable的表,其中包含2列SourceTableSourceId以及其他一些表ParentTable1ParentTable2等。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM