在返回结果之前,有没有办法过滤实体的结果? 所以说First或Find或者我选择用于对抗实体的任何方法都不会返回超过3个月的任何东西。此外,如果我包含实体,它也将被过滤。我试图使用它来实现软删除等
我希望这可以在某种程度上在内部完成,如果可能的话我可以说_db.SmallGroups.ToList()
并且它会知道哪些记录没有带回来(即旧记录,IsDeleted ==真实记录)我不想必要时,必须将此逻辑放在每个查询点
先谢谢
答案 0 :(得分: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);