0

重複の可能性:
Soft Delete Entity Framework Code First

結果が返される前にエンティティの結果をフィルタリングする方法はありますか? つまり、First または Find など、エンティティに対して使用することを選択したメソッドは、3 か月より古いものを返さないとしましょう。また、エンティティを含めると、エンティティもフィルタリングされます。これを使用して、とりわけソフト削除を実装しようとしています

可能であれば何らかの方法でこれを内部的に実行_db.SmallGroups.ToList()したいので、どのレコードを戻さないか (つまり、古いレコード、IsDeleted==true レコード) を知ることができます。このロジックを毎回入れる必要はありません。可能であればクエリポイント

前もって感謝します

4

1 に答える 1

0

もちろん、WHERE句条件を指定するだけです

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

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

アップデート

あなたのコメントに基づいて...

実際、 where条件として再利用できる式を作成できます。

これは私が作成した拡張メソッドで、Containsタイプの条件に対してそれを行います (元のソースは 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);
于 2012-10-03T17:31:32.770 に答える