Nhibernate子查询 - 无法解析x类型的属性

时间:2013-06-07 17:49:27

标签: c# sql nhibernate orm fluent-nhibernate

我需要一些帮助来找出一个应该基于一对多关系进行过滤的查询。我有一个表'Product'和'ProductType'。 '产品'有很多'ProductType'。这些模型运行良好我无法弄清楚如何根据'ProductType'记录过滤'产品'记录。

在这个例子中,我想选择所有'Product',其中Product.Name ==“somename”&& Product.Version ==“9.6”。我想在ProductType.Type ==“someType”中过滤这些结果。 以下是抛出异常:

  

无法解析属性:ProductType of:my.namespace.ProductType

我正在使用Ayende博客的示例:Query Examples

 var product = _session.CreateCriteria<Product>()
                              .Add(Restrictions.Eq("Name", "somename"))
                              .Add(Restrictions.Eq("Version", "9.6"))
                              .Add(Subqueries.PropertyIn("Id",
                                                         DetachedCriteria.For<ProductType>()
                                                                         .SetProjection(Projections.Property("Product.Id"))
                                                                         .CreateCriteria("ProductType")
                                                                         .Add(Restrictions.Eq("Type", "someType"))
                                       )).List<Product>().SingleOrDefault();

我关门了吗?有人可以给我一些帮助吗?谢谢!

修改

这让我很亲近。如果我删除第二个CreateCriteria,我会返回一个填充了类型的产品。一旦我将联接添加回来......我得到0结果。

 var products = _session.CreateCriteria("Product")
                                   .Add(Restrictions.Eq("Name", "somename"))
                                   .Add(Restrictions.Eq("Version", "9.6")) //This works
                                   .CreateCriteria("Types", "productTypes",   JoinType.LeftOuterJoin)
                                   .Add(Restrictions.Eq("Type", "typename")).List<Product>();

            return products.FirstOrDefault();

1 个答案:

答案 0 :(得分:0)

非常接近 - 你只需要告诉CreateCriteria如何获得ProductType。例如:

var product = _session.CreateCriteria<Product>()
    .Add(Restrictions.Eq("Name", "somename"))
    .Add(Restrictions.Eq("Version", "9.6"))
    .Add(Subqueries.PropertyIn("Id",
         DetachedCriteria.For<ProductType>()
        .SetProjection(Projections.Property("Product.Id"))
        .CreateCriteria("Product.ProductType", JoinType.InnerJoin)
        .Add(Restrictions.Eq("Type", "someType"))
     ))
     .List<Product>()
     .SingleOrDefault();