Kiểm tra bài viết này ra để làm những gì bạn muốn:
http://www.albahari.com/nutshell/predicatebuilder.aspx
này hoạt động giống như một giấc mơ. Tôi chủ yếu cắt và dán mã của họ và nhận được trở lại này (với tôi dữ liệu chương trình riêng của khóa học):
SELECT [t0].[Id], [t0].[DateCreated], [t0].[Name] ...
FROM [dbo].[Companies] AS [t0]
WHERE ([t0].[Name] LIKE @p0) OR ([t0].[Name] LIKE @p1)
Đây là mã tôi chạy cho bằng chứng của khái niệm:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq.Expressions;
namespace PredicateTest
{
class Program
{
static void Main(string[] args)
{
DataClasses1DataContext dataContext = new DataClasses1DataContext();
Program p = new Program();
Program.SearchCompanies("test", "test2");
var pr = from pi in dataContext.Companies.Where(Program.SearchCompanies("test", "test2")) select pi;
}
DataClasses1DataContext dataContext = new DataClasses1DataContext();
public static Expression<Func<Company, bool>> SearchCompanies(
params string[] keywords)
{
var predicate = PredicateBuilder.False<Company>();
foreach (string keyword in keywords)
{
string temp = keyword;
predicate = predicate.Or(p => p.Name.Contains(temp));
}
return predicate;
}
}
public static class PredicateBuilder
{
public static Expression<Func<T, bool>> True<T>() { return f => true; }
public static Expression<Func<T, bool>> False<T>() { return f => false; }
public static Expression<Func<T, bool>> Or<T>(this Expression<Func<T, bool>> expr1,
Expression<Func<T, bool>> expr2)
{
var invokedExpr = Expression.Invoke(expr2, expr1.Parameters.Cast<Expression>());
return Expression.Lambda<Func<T, bool>>
(Expression.OrElse(expr1.Body, invokedExpr), expr1.Parameters);
}
public static Expression<Func<T, bool>> And<T>(this Expression<Func<T, bool>> expr1,
Expression<Func<T, bool>> expr2)
{
var invokedExpr = Expression.Invoke(expr2, expr1.Parameters.Cast<Expression>());
return Expression.Lambda<Func<T, bool>>
(Expression.AndAlso(expr1.Body, invokedExpr), expr1.Parameters);
}
}
}
tôi d đề nghị truy cập trang web để biết mã và giải thích.
(Tôi để lại câu trả lời đầu tiên bởi vì nó hoạt động tốt nếu bạn cần một tuyên bố IN)
Nguồn
2009-02-06 15:49:18
Đó chắc chắn nên làm việc –
Cảm ơn ý tưởng Matthew, nhưng điều đó tạo ra các SQL sau đây:.. CHỌN [t0] [Text] FROM [dbo] [Bảng] AS [t0] ĐÂU [t0 ]. [Văn bản] IN (@ p0) Tìm kiếm cột văn bản trong mỗi mục của mảng thay vì tìm kiếm từng mục của mảng trong cột văn bản. – bjallen