Linq To Sql進階系列(七)動態查詢續及CLR與SQL在某些細節上的差別

來源:互聯網
上載者:User

在上面一篇文章Linq To Sql進階系列(六)中,我們提到了使用object的動態查詢。本文在上文的 基礎上,再做更加深入的引申。同時修正上文中一些不妥的地方。

1, object的動態查詢續

首先要做的事情,就是將Find的函數改成擴充方法。擴充方法只能放在靜態類裡,而且它的第一個參 數必須帶this關鍵字。在上文中,作者留下了一個迷題。當需要or條件時,又該如何做呢?本文也將這 個問題給出回答。但是對於動態Like的條件,筆者依然還沒有找到一個較好的方法。為了增加or條件, 函數的聲明也再一次被改動。如下:

public static IQueryable<TEntity> Find<TEntity>(this IQueryable<TEntity> source, TEntity obj, bool isAnd) where TEntity : class

在上文中,我們還碰到了System.Nullable<int>此類類型不支援的問題。其實這個地方主要原 因在於我們構造right端的Expression Tree時,沒有給它參數。那麼這個問題通過Expression right = Expression.Constant(p.GetValue(obj, null), p.PropertyType); 可以得到修複。那整個函數修改後 ,如下:

public static IQueryable<TEntity> Find<TEntity>(this IQueryable<TEntity> source, TEntity obj, bool isAnd) where TEntity : class
{
        if (source == null)
            throw new ArgumentNullException("Source can't be null!!");
        //獲得所有property的資訊
        PropertyInfo[] properties = obj.GetType().GetProperties (BindingFlags.Public | BindingFlags.Instance);

        Expression condition = null;
        //先構造了一個ParameterExpression對象,這裡的c,就是Lambda表達中的參數。( c=>) 
        //本變數被移出了foreach迴圈
        ParameterExpression param = Expression.Parameter(typeof(TEntity), "c");
        //遍曆每個property
        foreach (PropertyInfo p in properties)
        {
            if (p != null)
            {
                Type t = p.PropertyType;
                //只支援value型和string型的影射
                if (t.IsValueType || t == typeof(string))
                {
                    //如果不為null才算做條件
                    if (p.GetValue(obj, null) != null)
                    {
                        //SQL Server does not support comparison of TEXT, NTEXT, XML and IMAGE ,etc
                        /**////Only support BigInt,Bit,Char,Decimal,Money,NChar,Real,
                        ///Int,VarChar,SmallMoney,SmallInt,NVarChar,NVarChar(MAX),VarChar(MAX)
                        Attribute attr = Attribute.GetCustomAttribute(p, typeof(ColumnAttribute));
                        if (attr != null)
                        {
                            string dbType = (attr as ColumnAttribute).DbType;
                            if (dbType.Contains("Text") || dbType.Contains("NText")
                                || dbType.Contains("Xml") || dbType.Contains("Image")
                                || dbType.Contains ("Binary") || dbType.Contains("DateTime")
                                || dbType.Contains ("sql_variant") || dbType.Contains("rowversion")
                                || dbType.Contains ("UniqueIdentifier") || dbType.Contains("VarBinary(MAX)"))
                            {
                                continue;
                            }
                        }
                        //構造運算式的右邊,值的一邊
                        Expression right = Expression.Constant (p.GetValue(obj, null), p.PropertyType);
                        //構造運算式的左邊,property一端。
                        Expression left = Expression.Property (param, p.Name);
                        //產生篩選條件運算式。即c.CustomerID == "Tom"
                        Expression filter = Expression.Equal(left, right);
                        if (condition == null)
                        {
                            condition = filter;
                        }
                        else
                        {
                            if (isAnd)
                                condition = Expression.And(condition, filter);
                            else
                                condition = Expression.Or (condition, filter);
                        }
                    }
                }
            }
        }
        if (condition != null)
        {
            Expression<Func<TEntity, bool>> pred = Expression.Lambda<Func<TEntity, bool>>(condition, param);
            return source.Where(pred);
        } 
        return source;

}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.