2010-04-30 72 views
2

我在构建正确的标准以执行特定查询时遇到了一些麻烦 - 经过与Google教授的一个下午咨询,我希望有人能指出我正确的方向。如何在有<any>关联时编写标准查询

我有两个实体:OutputTsDefNamedAttribute

我试图做的是要找到具有特定NamedAttribute值的所有OutputTsDef

我可以写一个分离的标准来寻找有 所有NamedAttributes给定的名称和值:

 var attributesCriteria 
      = DetachedCriteria.For<INamedAttribute>() 
       .Add(Expression.Eq("Name", "some name")) 
       .Add(Expression.Eq("Value", "some value")); 

如何注入这在一个查询OutputTsDef限制的结果?

 var criteria 
      = nHibernateSession.CreateCriteria(typeof(IOutputTsDefEntity)); 
     // What do I write here? 
     var results = criteria.List(); 

NamedAttribute看起来是这样的 - 注意使用[Any]因为我们可以有多种实体的 NamedAttributes

[AttributeIdentifier("DbKey", Name = "Id.Column", Value = "NamedAttributeID")] 
[Class(Table = "NamedAttributes")] 
public class NamedAttribute : BusinessEntity, INamedAttribute 
{ 
    [Any(0, Name = "Entity", MetaType = "System.String", IdType = "System.Int32")] 
    [MetaValue(1, Class = "Sample.OutputTsDef, Sample.Entities", Value = "OTD")] 
    [MetaValue(2, Class = "Sample.OutputTimeSeriesAttributesEntity, Sample.Entities", Value = "OTA")] 
    [Column(3, Name = "OwnerType")] 
    [Column(4, Name = "OwnerKey")] 
    public virtual IBusinessEntity Entity { get; set; } 

    [Property(Column = "Name")] 
    public virtual string Name { get; set; } 

    [Property(Column = "Value")] 
    public virtual string Value { get; set; } 

    ... omitted ... 

}

在常规的SQL,我只是包括一个额外的 “where” 子句是这样的:

where OutputTsDefId 
     in (select distinct OwnerKey 
      from NamedAttributes 
      where Name = ? 
      and Value = ? 
      and OwnerType = 'OTD') 

我缺少什么?

(问题也张贴到NHUsers邮件列表 - 我会任何有用的信息从那里复制,在这里。)

回答

0

这是我落得这样做 - 以这种方式嵌入SQL子查询检查:

const string subquery 
    = "{alias}.OutputTsDefId in " 
     +"(select OwnerKey " 
     + " from NamedAttributes na " 
     + " where na.Name = ? and na.Value = ? and OwnerType='OTD')"; 
criteria.Add(
    Expression.Sql(
     subquery, 
     new object[] { attributeFilter.Name, attributeFilter.Value }, 
     new IType[] { NHibernateUtil.String, NHibernateUtil.String })); 

这不是理想的 - 我真的不喜欢以这种方式隧道过去NHibernate的。但是,它完成了工作,这很重要。

我仍然对找到一个纯粹的NHibernate解决方案感兴趣,如果有的话。