我有两个实体:
public class Parent
{
public virtual int Id { get; set; }
}
public class Child
{
public virtual int Id { get; set; }
public virtual int ParentId
{
get
{
if (Parent != null)
return Parent.Id;
return -1;
}
set
{
if (Parent != null)
Parent = new Parent();
Parent.Id = value;
}
}
protected virtual Parent Parent
{
get;
set;
}
}
像这样设置 Parent
属性是为了简化 API 方面,我不想更改它以公开公开此属性。我重写了 Child
类的映射来适应这一点:
public class ChildMappingOverrides : IAutoMappingOverride<Child>
{
public void Override(AutoMapping<Child> mapping)
{
mapping.References<Parent>(Reveal.Member<Child>("Parent")).Column("Parent_id");
mapping.IgnoreProperty(x => x.ParentId);
}
}
现在,如果我想查询给定父 ID 的所有 Child
对象,我将执行以下操作:
session.QueryOver<Child>().Where(c => c.ParentId == 1);
但是,这会引发QueryException
:
could not resolve property: ParentId of: My.Namespace.Child
如何检索具有特定 Parent
Id 的 Child
对象集?
最佳答案
未经测试,但你可以尝试这个:
session.QueryOver<Child>()
.Where(Restrictions.Eq(
Projections.SqlProjection(
"{alias}.Parent_id as ParentId",
new[] { "ParentId" },
new[] { NHibernateUtil.Int32 }), 1))
.List<Child>();
您将无法在任何 NHibernate 查询中查询未映射的关联,但这至少可以最大限度地减少编译时检查的损失。
据我所知,这有些有限。 {alias}
将始终被 root 实体的别名替换,这意味着如果您想对不以 开头的更复杂的查询执行此操作 child
,你可能不走运。
关于c# - 使用被忽略的属性的 QueryOver,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25814075/