问题
I'm trying to implement search functionality in an ASP.NET MVC 2 application. I create an expression based on criteria entered by the user:
public ViewResult FindCustomer( string forename, string familyname, DateTime? dob)
{
Expression<Func<Customer, bool>> searchCriteria = p => (
forename.IsNullOrEmpty() ? true : p.Forename == forename
&& familyname.IsNullOrEmpty() ? true : p.FamilyNames.Any(n => n.Name == familyname)
&& dob.HasValue ? true : p.DOB == dob
);
which then gets passed to a method in the repository
IQueryable<Customer> customers = CustomerRepository.FilterBy(searchCriteria);
The problem is when I run this I get the following exception
System.InvalidCastException: Unable to cast object of type 'NHibernate.Hql.Ast.HqlCast' to type 'NHibernate.Hql.Ast.HqlBooleanExpression'
According to this the problem is the use of the conditional operator in the expression.
So I suppose I have to create the Expression some other way but I'm not sure how to do that. I'm pretty new to Linq so any help would be gratefully accepted!
回答1:
What about dynamically create your query? Like this:
var customers = CustomerRepository.AllEntities();
if (!forename.IsNullOrEmpty())
customers = customers.Where(p => p.Forename == forename);
if (!familyname.IsNullOrEmpty())
customers = customers.Where(p => p.FamilyNames.Any(n => n.Name==familyname));
if (dob.HasValue)
customers = customers.Where(p => p.DOB == dob);
I don't know if this works but I think this could be more efficient.
来源:https://stackoverflow.com/questions/9774598/conditional-operator-in-linq-expression-causes-nhibernate-exception