在LINQ表达式有条件的经营者造成异常的NHibernate [英] Conditional operator in Linq Expression causes NHibernate exception

查看:74
本文介绍了在LINQ表达式有条件的经营者造成异常的NHibernate的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在ASP.NET MVC 2应用程序中实现搜索功能。我创建基于用户输入的条件表达式:

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.

所以,我想我必须创建表达一些其他的方式,但我不知道该怎么做。我是很新,这样的Linq任何帮助将欣然接受!

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!

推荐答案

什么动态创建查询?像这样的:

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.

这篇关于在LINQ表达式有条件的经营者造成异常的NHibernate的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆