Conditional operator in Linq Expression causes NHibernate exception

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-04 03:16:53

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!