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条件。

这是我为包含条件类型编写的扩展方法(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 回答