NHibernate ICriteria 查询,包含用于高级搜索的组件和集合

发布于 2024-07-21 11:34:35 字数 2660 浏览 10 评论 0原文

我正在为我的 ASP.NET MVC 应用程序构建高级搜索表单。

我有一个客户对象,带有地址组件: 流畅的 NHibernate 映射:

       public CustomerMap()
    {
        WithTable("Customers");

        Id(x => x.Id)
            .WithUnsavedValue(0)
            .GeneratedBy.Identity();

        Map(x => x.Name);
        Map(x => x.Industry);

        Component(x => x.Address, m =>
        {
            m.Map(x => x.AddressLine);
            m.Map(x => x.City);
            m.Map(x => x.State);
            m.Map(x => x.Zip);
        });

在我的 Customer 类 ctor 中,为了防止空对象,我有以下内容:

public Customer()
{
    Address = new Address();
}

我的搜索表单具有以下字段可供用户搜索:

  • 客户名称
  • 城市
  • 行业

所有这些字段都是可选的。

我的 NHibernate Criteria 如下所示(使用 ASP.NET MVC 模型绑定器从表单传入客户):

            var p = Session.CreateCriteria(typeof(Customer))
            .Add(Example.Create(customer).ExcludeZeroes().IgnoreCase().EnableLike())
            .SetProjection(Projections.ProjectionList()
                               .Add(Projections.Property("Id"), "Id")
                               .Add(Projections.Property("Name"), "Name")
                               .Add(Projections.Property("Address.City"), "City")
                               .Add(Projections.Property("Address.State"), "State")
                               .Add(Projections.Property("PhoneNumber"), "PhoneNumber"))
            .AddOrder(Order.Asc("Name"))
            .SetResultTransformer(NHibernate.Transform.Transformers.AliasToBean(typeof(CustomerDTO)));

        return p.List<CustomerDTO>() as List<CustomerDTO>;

请注意,我正在使用 .ExcludeZeroes() 来排除空值和零默认值。 这是必需的,因为我的 Customer 对象有一些 INT(为了简洁起见,在本文中排除了这些 INT),这些 INT 在查询中默认为零 (0),从而导致不正确的查询。

如果我在所有字段为空的情况下运行此命令(好的,因为它们是可选的),生成的 SQL 如下所示:

SELECT   this_.Id          as y0_,
         this_.Name        as y1_,
         this_.City        as y2_,
         this_.State       as y3_,
         this_.PhoneNumber as y4_
FROM     Customers this_
WHERE    (lower(this_.Industry) like '' /* @p0 */
          and lower(this_.State) like '' /* @p1 */)
ORDER BY y1_ asc

Industry 和 State 是 Web 表单中的下拉菜单,但在上面的示例中,我将它们留空。 但 ExcludeZeroes() 声明似乎不适用于这些字段。

如果我在标准之前手动检查:

if (customer.Address.State == "")
{
    customer.Address.State = null;
}

并对行业执行相同的操作,则标准将起作用。

我假设这与我在客户构造函数中初始化地址对象有关。 我不想改变这一点,但我不知道还有另一种方法可以使 Criteria 工作而无需手动检查表单中的空字符串值(从而消除了使用 ICriteria 的示例对象的优势)。

为什么? 我怎样才能让这个 Criteria 查询起作用?

I'm building an advanced search form for my ASP.NET MVC app.

I have a Customer object, with an Address Component:
Fluent NHibernate mapping:

       public CustomerMap()
    {
        WithTable("Customers");

        Id(x => x.Id)
            .WithUnsavedValue(0)
            .GeneratedBy.Identity();

        Map(x => x.Name);
        Map(x => x.Industry);

        Component(x => x.Address, m =>
        {
            m.Map(x => x.AddressLine);
            m.Map(x => x.City);
            m.Map(x => x.State);
            m.Map(x => x.Zip);
        });

In my Customer class ctor, to prevent null objects, I have the following:

public Customer()
{
    Address = new Address();
}

My search form has the following fields available to the user to search on:

  • Customer Name
  • City
  • State
  • Industry

All of these fields are optional.

My NHibernate Criteria looks like this (customer is being passed in from the form using the ASP.NET MVC Model Binder):

            var p = Session.CreateCriteria(typeof(Customer))
            .Add(Example.Create(customer).ExcludeZeroes().IgnoreCase().EnableLike())
            .SetProjection(Projections.ProjectionList()
                               .Add(Projections.Property("Id"), "Id")
                               .Add(Projections.Property("Name"), "Name")
                               .Add(Projections.Property("Address.City"), "City")
                               .Add(Projections.Property("Address.State"), "State")
                               .Add(Projections.Property("PhoneNumber"), "PhoneNumber"))
            .AddOrder(Order.Asc("Name"))
            .SetResultTransformer(NHibernate.Transform.Transformers.AliasToBean(typeof(CustomerDTO)));

        return p.List<CustomerDTO>() as List<CustomerDTO>;

Notice that I'm using .ExcludeZeroes() to exclude nulls and zero-defaulted values. This is required since my Customer object has some INTs (excluded in this post for brevity) that would default to zero (0) in the query, resulting in incorrect queries.

If I run this with all the fields blank (ok, since they are optional), the resulting SQL looks like this:

SELECT   this_.Id          as y0_,
         this_.Name        as y1_,
         this_.City        as y2_,
         this_.State       as y3_,
         this_.PhoneNumber as y4_
FROM     Customers this_
WHERE    (lower(this_.Industry) like '' /* @p0 */
          and lower(this_.State) like '' /* @p1 */)
ORDER BY y1_ asc

Industry and State are drop-downs in the web form, but in the above example, I left them blank. But the ExcludeZeroes() declaration doesn't seem to apply to those fields.

If I manually check before the Criteria:

if (customer.Address.State == "")
{
    customer.Address.State = null;
}

and do the same for Industry, the Criteria will then work.

I'm assuming this has to do with me initializing the Address object in my Customer ctor. I hate to change that, but I don't know of another way of making the Criteria work without manually checking for empty string values from the form (thus eliminating the advantage to using a Example object with ICriteria).

Why? How can I get this Criteria query to work?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

鹤舞 2024-07-28 11:34:35

使用属性选择器忽略 null 或空字符串。

using System;
using NHibernate.Criterion;
using NHibernate.Type;


namespace Sample
{

    /// <summary>
    /// Implementation of <see cref="Example.IPropertySelector"/> that includes the
    /// properties that are not <c>null</c> and do not have an <see cref="String.Empty"/>
    /// returned by <c>propertyValue.ToString()</c>.
    /// </summary>
    /// <remarks>
    /// This selector is not present in H2.1. It may be useful if nullable types
    /// are used for some properties.
    /// </remarks>
    public class NoValuePropertySelector : Example.IPropertySelector
    {
        #region [ Methods (2) ]

        // [ Public Methods (1) ]

        /// <summary>
        /// Determine if the Property should be included.
        /// </summary>
        /// <param name="propertyValue">The value of the property that is being checked for inclusion.</param>
        /// <param name="propertyName">The name of the property that is being checked for inclusion.</param>
        /// <param name="type">The <see cref="T:NHibernate.Type.IType"/> of the property.</param>
        /// <returns>
        ///     <see langword="true"/> if the Property should be included in the Query,
        /// <see langword="false"/> otherwise.
        /// </returns>
        public bool Include(object propertyValue, String propertyName, IType type)
        {
            if (propertyValue == null)
            {
                return false;
            }

            if (propertyValue is string)
            {
                return ((string)propertyValue).Length != 0;
            }

            if (IsZero(propertyValue))
            {
                return false;
            }
            else
            {
                return true;
            }
        }

        // [ Private Methods (1) ]

        private static bool IsZero(object value)
        {
            // Only try to check IConvertibles, to be able to handle various flavors
            // of nullable numbers, etc. Skip strings.
            if (value is IConvertible && !(value is string))
            {
                try
                {
                    return Convert.ToInt64(value) == 0L;
                }
                catch (FormatException)
                {
                    // Ignore
                }
                catch (InvalidCastException)
                {
                    // Ignore
                }
            }

            return false;
        }


        #endregion [ Methods ]
    }

}

Use a property selector to ignore null or empty strings.

using System;
using NHibernate.Criterion;
using NHibernate.Type;


namespace Sample
{

    /// <summary>
    /// Implementation of <see cref="Example.IPropertySelector"/> that includes the
    /// properties that are not <c>null</c> and do not have an <see cref="String.Empty"/>
    /// returned by <c>propertyValue.ToString()</c>.
    /// </summary>
    /// <remarks>
    /// This selector is not present in H2.1. It may be useful if nullable types
    /// are used for some properties.
    /// </remarks>
    public class NoValuePropertySelector : Example.IPropertySelector
    {
        #region [ Methods (2) ]

        // [ Public Methods (1) ]

        /// <summary>
        /// Determine if the Property should be included.
        /// </summary>
        /// <param name="propertyValue">The value of the property that is being checked for inclusion.</param>
        /// <param name="propertyName">The name of the property that is being checked for inclusion.</param>
        /// <param name="type">The <see cref="T:NHibernate.Type.IType"/> of the property.</param>
        /// <returns>
        ///     <see langword="true"/> if the Property should be included in the Query,
        /// <see langword="false"/> otherwise.
        /// </returns>
        public bool Include(object propertyValue, String propertyName, IType type)
        {
            if (propertyValue == null)
            {
                return false;
            }

            if (propertyValue is string)
            {
                return ((string)propertyValue).Length != 0;
            }

            if (IsZero(propertyValue))
            {
                return false;
            }
            else
            {
                return true;
            }
        }

        // [ Private Methods (1) ]

        private static bool IsZero(object value)
        {
            // Only try to check IConvertibles, to be able to handle various flavors
            // of nullable numbers, etc. Skip strings.
            if (value is IConvertible && !(value is string))
            {
                try
                {
                    return Convert.ToInt64(value) == 0L;
                }
                catch (FormatException)
                {
                    // Ignore
                }
                catch (InvalidCastException)
                {
                    // Ignore
                }
            }

            return false;
        }


        #endregion [ Methods ]
    }

}
揽清风入怀 2024-07-28 11:34:35

我对 QBE 也有同样的问题。 我还认为,按示例查询是对对象(和关联对象)进行通用搜索的一种非常好的方法。 已经存在 ExcludeNones/Nulls/Zeros。 还应该有一个排除空字符串(“”)的选项。

I have the same issue with QBE. I also think that the Query by Example is a very nice approach for generic searches on an object (and associates). There is already ExcludeNones/Nulls/Zeros. There should be an option to exclude empty strings ("") too.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文