2013-05-31 49 views
2

創建查詢我有一個DBML上下文查詢,看起來像這樣:的LINQ to SQL從字符串

var SQLQueryResult = (from activeTable in context.activeTabless 
         where (
           activeTable .AssignedTo == "Person1" || 
           activeTable .AssignedTo == "Person2" || 
           activeTable .AssignedTo == "Person3") 
        select new { ... }); 

我的問題是,我怎麼可以更新where字段,以便它可以有任意數量的or(基於用戶選擇,不只是三個)?

比方說,數字可以來自一個列表或數組。 這對於直接SQL很簡單,但不知道如何通過Linq到SQL來完成。

回答

5
var persons = new []{"Person1", "Person2", "Person3"}; 
var SQLQueryResult = (from activeTable in context.activeTabless 
         where (persons.Contains(activeTable .AssignedTo)) 
        select new { ... }); 

您可以檢查是否使用IEnumerable.Contains()擴展方法的集合中存在的東西。

+1

這是一個解決方案,但您需要觀看出於至少兩件事情: 1)它不起作用,如果人們在SQL服務器上包含超過2100個項目 2)它在ansi列上工作非常緩慢 – Giedrius

+0

這就是它。謝謝。它應該是好的,因爲它永遠不會達到2100個項目 –

1

您可以通過使用表達式來動態創建查詢,以便能夠構建謂詞的位置。更多詳細信息,你可以在這裏找到一個樣本:Linq dynamic queries

1

您可以使用謂詞建設者(實用類):

using System; 
using System.Linq; 
using System.Linq.Expressions; 

public static class PredicateBuilder { 
    public static Expression<Func<T, bool>> Make<T>() { 
    return null; 
    } 

    public static Expression<Func<T, bool>> Make<T>(this Expression<Func<T, bool>> predicate) { 
    return predicate; 
    } 

    public static Expression<Func<T, bool>> Or<T>(this Expression<Func<T, bool>> expr, Expression<Func<T, bool>> orExpression) { 
    if (expr == null) { 
     return orExpression; 
    } 
    var invokedExpr = Expression.Invoke(orExpression, expr.Parameters.Cast<Expression>()); 
    return Expression.Lambda<Func<T, bool>>(Expression.Or(expr.Body, invokedExpr), expr.Parameters); 
    } 

    public static Expression<Func<T, bool>> And<T>(this Expression<Func<T, bool>> expr, Expression<Func<T, bool>> andExpression) { 
    if (expr == null) { 
     return andExpression; 
    } 
    var invokedExpr = Expression.Invoke(andExpression, expr.Parameters.Cast<Expression>()); 
    return Expression.Lambda<Func<T, bool>>(Expression.And(expr.Body, invokedExpr), expr.Parameters); 
    } 
} 

用法:

public IEnumerable<Squad> GetSquadsByIDs(IEnumerable<int> squadIDs) { 
    if (squadIDs == null || !squadIDs.Any()) { 
    throw new ArgumentNullException("squadIDs"); 
    } 
    var condition = PredicateBuilder.Make<Squad>(s => false); 
    foreach (var squadID in squadIDs) { 
    int squadIDValue = squadID; 
    condition = PredicateBuilder.Or<Squad>(condition, s => s.SquadID == squadIDValue); 
    } 
    var db = m_DalContextProvider.GetContext(); 
    return db.Squads.Where(condition); 
} 
+0

此解決方案有一個虛假的遞歸問題,這裏描述:http://sharpit.apphb.com/Posts/Post/33 – Giedrius

相關問題