2012-10-03 44 views
0

可能重複:
Soft Delete Entity Framework Code First實體框架代碼優先篩選結果進行檢索

有沒有辦法來篩選實體結果的返回結果之前? 所以說先選擇或者選擇或者我選擇用來反對實體的任何方法都不會返回比3個月更長的東西。同樣,如果我包含實體,它也會被過濾掉。我試圖用這個來實現軟刪除等

我想這樣做是在某種程度上可能的內部,所以我可以說_db.SmallGroups.ToList()它會知道什麼記錄不帶回(即較舊的記錄,IsDeleted ==真實記錄)我不想將不得不把這個邏輯在每次查詢點,如果可能的

由於提前

+0

這將是東西在存儲庫中執行。 –

+1

但你爲什麼要問[再](http://stackoverflow.com/questions/12698793/soft-delete-entity-framework-code-first)? –

回答

0

當然,你可以在那裏條款指定條件

DateTime threeMonthsAgo = DateTime.Now.AddMonths(-3); 

var results = 
    (from t in context.MyTable where t.TheTime > threeMonthsAgo select t).First(); 

UPDATE

基於您的評論...

你的確可以建立一個可以重用的其中條件表達式。

下面是一個擴展方法我寫的這是否爲包含類型的條件(原始來源的XML註釋引用)

/// <summary> 
/// Extension method that enables .Contains(obj) like functionality for Linq to Entities. 
/// 
/// Source: http://www.velocityreviews.com/forums/t645784-linq-where-clause.html 
/// </summary> 
/// <typeparam name="TElement">The element being evaluated by the Where clause</typeparam> 
/// <typeparam name="TValue">The value to match</typeparam> 
/// <param name="valueSelector">Lamda for selecting matching values</param> 
/// <param name="values">IEnumerable of the values</param> 
/// <returns>Expression consumable by Linq to Entities that reflects semantics of .Contains(value)</returns> 
/// <remarks> 
/// Usage: 
/// 
/// Replace expression like 
/// 
/// where ChildrenIDs.Contains(items.CategoryID) 
/// 
/// with 
/// 
/// .Where((BuildContainsExpression<Item, int>(item => item.CategoryID, ChildrenIDs)) 
/// 
/// NOTE: If the item collection is large, the SQL query will be as well. 
/// </remarks> 
static public Expression<Func<TElement, bool>> BuildContainsExpression<TElement, TValue>(Expression<Func<TElement, TValue>> valueSelector, IEnumerable<TValue> values) 
{ 
    if (null == valueSelector) 
    { 
     throw new ArgumentNullException("valueSelector"); 
    } 
    if (null == values) { throw new ArgumentNullException("values"); } 

    ParameterExpression p = valueSelector.Parameters.Single(); 
    if (!values.Any()) 
    { 
     return e => false; 
    } 

    var equals = values.Select(value => (Expression)Expression.Equal(valueSelector.Body, Expression.Constant(value, typeof(TValue)))); 
    var body = equals.Aggregate<Expression>((accumulate, equal) => Expression.Or(accumulate, equal)); 
    return Expression.Lambda<Func<TElement, bool>>(body, p); 
} 

使用

HashSet<long> productCodes = new HashSet<long>(); // Populate with some product codes to match 

productCodeWhere = LinqToEntitiesUtil.BuildContainsExpression<Verbatim, long>(v => v.ProductCode, productCodes); 

var matching = (from v in ctx.MyTable where MY_CONDITIONS select v) 
    .Where(productCodeWhere); 
+0

我的歉意。 我的意思是更內在的東西,所以如果我說'_db.SmallGroups.ToList()'它會知道在3個月前忽略說或者那些用IsDeleted,這樣我就不必每次強制執行這些規則查詢點,而是在一個地方。謝謝。 – Jordan

+0

添加了一個如何重用* where *表達式的示例。 –