/* 作者:道法自然
* 個人郵件:[email protected]
* 2014-10-1
*/
Lambda表達式轉SQL語句類庫
源碼下載:http://download.csdn.net/detail/xftyyyyb/8044085
一、可以達到的功能
本功能類庫主要提供給代碼中使用Lambda表達式,後需轉成SQL的條件語句這一需求。
二、不能做的
1、本類庫不能解析Linq語句;
2、不能解析SQL中的Select部分;
三、案例:
1、以Northwind數據庫Customers表為例,為使問題簡單,僅用部分字段演示
/// <summary>
/// 客戶管理
/// </summary>
public class Customers
{
/// <summary>
/// 客戶ID
/// </summary>
public string CustomerID { get; set; }
/// <summary>
/// 公司名稱
/// </summary>
public string CompanyName { get; set; }
/// <summary>
/// 地址
/// </summary>
public string Address { get; set; }
}
2、可能會有如下方法訪問數據庫
public static Customers Data_Fetch(string aiWhere, string aiOrderBy)
{
var cnstr = ConfigurationManager.ConnectionStrings["DemoConnectionString"].ConnectionString;
Customers aiCustomers = new Customers();
StringBuilder aisd = new StringBuilder();
using (SqlConnection cn = new SqlConnection(cnstr))
{
#region 數據訪問
#region 查詢SQL語句
aisd.Append(" SELECT ");
aisd.Append(" CustomerID,CompanyName,Address ");
aisd.Append(" FROM Customers ");
aisd.Append(aiWhere);
aisd.Append(aiOrderBy);
#endregion
cn.Open();
using (SqlCommand cmd = new SqlCommand(aisd.ToString(), cn))
{
using (SqlDataReader myDataReader = cmd.ExecuteReader())
{
if (myDataReader.HasRows)
{
myDataReader.Read();
aiCustomers = new Customers
{
#region 類賦值
CustomerID = (string)myDataReader["CustomerID"],
CompanyName = (string)myDataReader["CompanyName"],
Address = (string)myDataReader["Address"]
#endregion
};
}
};
}
#endregion
}
return aiCustomers;
}
3、構建一個表達式方法
public static class DbCustomersTest
{
/// <summary>
/// 構建一個表達式方法
/// </summary>
/// <param name="aiExp">表達式</param>
/// <returns></returns>
public static Customers GetCustomers(Expression<Func<IQueryable<Customers>, IQueryable<Customers>>> aiExp)
{
AiExpConditions<Customers> expc = new AiExpConditions<Customers>();
expc.Add(aiExp);
return Customers.Data_Fetch(expc.Where(), expc.OrderBy());
}
}
4、調用用例測試
Customers aic = DbCustomersTest.GetCustomers(c => c.Where(o => o.CustomerID == "ALFKI"));
Customers aic2 = DbCustomersTest.GetCustomers(c => c.Where(o => o.CustomerID.Contains("CO")).OrderBy(o=>o.CompanyName));
參考代碼:UserInfo .Where ( u => UserInfo .Where (m => m.DemoName.Contains ("s")) .Select (k => k.Id) .Contains (3) )
轉的具體代碼受限於你的上下文,因此是不可能給你寫出來你直接運行的。但原則都是相同的。要用到的有join,匿名類型(select的那些),entitiyfunction(如果你用entitiy framework)或者sqlmethods(如果你用了linq to sql)。