带有日期参数的条件where子句引发“没有支持的SQL转换”。使用C#在Linq to SQL中出错

问题描述:

我正在使用Visual C#2008和dot Net framework 4.5处理linq to sql项目。

我的查询如下

I'm working on a linq to sql project using Visual C# 2008 and dot Net framework 4.5.
my query is as follows

var q =
        from a in dc.GetTable<invoice_in>()
        join b in dc.GetTable<supplier>()
        on a.supplier_id equals b.id
        where a.invoice_date >= date_from
        select new Invoice_in(a.id, a.amount ?? 0, a.invoice_number ,
                              a.supplier_id ?? 0, a.supplier.s_name,
                              a.invoice_date ?? System.DateTime.Today);



invoce_in是一个linq类,而Invoice_in是我用类似结构定义的类。

当我把日期比较在最后一个查询中的where子句内,一切正常。但是我需要使用条件where,因为查询参数在主查询子句之后去了



我在前面的代码中添加了以下几行




invoce_in is a linq class while Invoice_in is a class I defined with a similar structure.
When I put the date comparison inside where clause within the last query, everything is OK. But I need to use a conditional where, as the query parameters goes after the main query clause

I added the following lines to the previous code

if (date_from != null)
            {
                q = q.Where(w => w.invoice_date >= date_from);
            } 



其中w.invoice_date是DateTime类型,它是Invoice_in类的数据成员(由我定义)。

添加最后几行代码会导致以下运行时错误:


Where w.invoice_date is of DateTime type and it is data member of the class Invoice_in (defined by me).
Adding that last lines of code causes the following runtime error:

"has no supported translation to SQL"





我在网上尝试过几十种方法,例如使用SQLMethods来比较日期和类似的东西,没什么用的是



请帮助...提前致谢...



I've tried dozens of methods on the web such as using SQLMethods for comparing dates and such stuff, nothing works

Please Help... Thanks in advance...

更改您的位置条件如下

change your where condition as below
var q =
           from a in dc.GetTable<invoice_in>()
           join b in dc.GetTable<supplier>()
           on a.supplier_id equals b.id
           where date_from!=null && a.invoice_date >= date_from
           select new Invoice_in(a.id, a.amount ?? 0, a.invoice_number ,
                                 a.supplier_id ?? 0, a.supplier.s_name,
                                 a.invoice_date ?? System.DateTime.Today);</supplier></invoice_in>











or

if (date_from != null)
{
    q = q.ToList().Where(w => w.invoice_date >= date_from);
}