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?