摘要:[LINQ]使用動態LINQ
nuGet安裝此套件:
System.Linq.Dynamic
新增動態LINQ類別,之後用來組合動態LINQ字串:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace WebAPIDataCenter.Library
{
//動態linq物件
public class DLinq
{
//欄位編號
private int ColCount = 0;
//linq字串
public string SQL = "";
//等於或是like
public enum EqualOrLike
{
Equal, Like
};
//加入一個欄位,並設定動態linq字串
public void AddColInfo(string ColName, object ColValue, EqualOrLike eqOrLike)
{
//如果裡面已經有別的欄位條件,就要先加上and
if (SQL != "")
{
SQL += " and ";
}
if (eqOrLike == EqualOrLike.Equal)
{
if(ColValue != null)
{
SQL += ColName + " == " + "@" + ColCount.ToString() + " ";
}
else
{
SQL += " null == @" + ColCount.ToString() + " ";
}
}
else
{
if (ColValue != null)
{
SQL += " " + ColName + ".Contains(@" + ColCount.ToString() + ") ";
}
else
{
SQL += " null == @" + ColCount.ToString() + " ";
}
}
ColCount++;
}
public override string ToString()
{
return SQL;
}
}
}
再加入一個新的EXTENTION METHOD,是用來配合微軟的System.Linq.Dynamic套件使用
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
//使用動態linq
using System.Linq.Dynamic;
namespace WebAPIDataCenter.Library
{
public static class Extensions
{
//IQueryable最後回傳的型態T,是根據Client端呼叫WhereDLinq者的型態而定
public static IQueryable WhereDLinq(this IQueryable data,string dLinq,params object[] values)
{
if (dLinq != "")
{
data = data.Where(dLinq, values);
}
else
{
//甚麼都不用做
}
return data;
}
}
}
實際的dbContext.cs類別的引用方式:
public IQueryable QueryEmp(int? EmployeeID = null, string LastName = null
, string FirstName = null)
{
//設定動態linq字串
DLinq dL = new DLinq();
string abc = dL.ToString();
dL.AddColInfo("EmployeeID", EmployeeID, DLinq.EqualOrLike.Equal);
dL.AddColInfo("LastName", LastName, DLinq.EqualOrLike.Like);
dL.AddColInfo("FirstName", FirstName, DLinq.EqualOrLike.Like);
var emps = db.Employees.WhereDLinq(dL.SQL, EmployeeID, LastName, FirstName)
.OrderBy("EmployeeID")
.AsQueryable();
return emps;
}
就是這樣而已
參考資料
Dynamic LINQ 讓 LINQ 的世界變的更美好 from blog.miniasp.com
Dynamic LINQ (Part 1: Using the LINQ Dynamic Query Library) from weblogs.asp.net/scottgu