C# 如何映射NHibernate变量表引用?

C# 如何映射NHibernate变量表引用?,c#,nhibernate,nhibernate-mapping,C#,Nhibernate,Nhibernate Mapping,有一个名为ChildTable的表,其中有两列SourceTable和SourceId以及一些其他表ParentTable1,ParentTable2,等等 当源表具有与父表关联的值(1->父表1,2->父表2)时,可以使用源Id中找到的Id连接到父表。例如,要获取与ParentTable1中的行关联的所有ChildTable行,可以通过以下查询实现: select * from ChildTable ct join ParentTable1 pt1 on ct.SourceTable =

有一个名为
ChildTable
的表,其中有两列
SourceTable
SourceId
以及一些其他表
ParentTable1
ParentTable2
,等等

源表
具有与父表关联的值(1->
父表1
,2->
父表2
)时,可以使用
源Id
中找到的Id连接到父表。例如,要获取与
ParentTable1
中的行关联的所有
ChildTable
行,可以通过以下查询实现:

select *
from ChildTable ct
join ParentTable1 pt1
  on ct.SourceTable = 1 and ct.SourceId = pt1.Id
我想将这2个
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)"));
以及Parent1类的儿童集合,包括:

mapper.Where("SourceTable = 1");
对于更新/插入,可能可以使用访问器实现,稍后将发布更新。

为什么不使用

类别:

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"));
});


在您想要的子类中,是Parent1Class类型的所有属性,还是Parent1/2/3Class类型的所有属性?啊,感谢您的注意,这是一个输入错误,它们是不同的类型。您有一个条件,需要根据SourceId使用where子句过滤多对一映射。您能确认SourceID已修复吗?这似乎是一个尚未解决的问题。这个问题似乎在寻找解决我问题的办法。
SourceId
被修复是什么意思?在
SourceId
列中可能有重复的值,但它们对于每个
SourceTable
都必须是唯一的。基本上,
SourceTable
SourceId
的组合是唯一的。如果每个SourceId指向不同的父表(ParentTable1、ParentTable2、ParentTable3),则可以将SourceId=1用于3行。谢谢。使用
child.parent is Parent1Class
更新父属性并使用LINQ进行查询。无法使
.Fetch(=>\uu.Parent)
正常工作,因为它在NHibernate.dll中引发了类型为“System.InvalidCastException”的异常,但未在用户代码中处理。其他信息:无法将类型为“NHibernate.type.AnyType”的对象强制转换为类型为“NHibernate.type.ComponentType”。使用
进行投影时出现相同错误。请选择(…)
。可能会发布另一个问题。当尝试使用cast/as在LINQ Where子句中对父级设置条件时,会遇到与上述问题相同的问题。您好@RăzvanFlaviusPanda您能解决此cast问题吗?
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')