簡體   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