我正在尝试查询实体以根据过滤器返回多行。
例如在SQL中我们有:
SELECT * FROM table WHERE field IN (1, 2, 3)
如何在LINQ to Entities中执行此操作?
答案 0 :(得分:4)
虽然我收到了一些快速答案,但我感谢大家。我收到的回复中显示的方法无效。
我必须继续搜索,直到我最终找到了一种方法,可以在Microsoft Forums的Frederic Ouellet的帖子中找到我需要的方法。
简而言之,这是下面的扩展方法:
public static IQueryable<T> WhereIn<T, TValue>(this IQueryable<T> source, Expression<Func<T, TValue>> propertySelector, params TValue[] values)
{
return source.Where(GetWhereInExpression(propertySelector, values));
}
public static IQueryable<T> WhereIn<T, TValue>(this IQueryable<T> source, Expression<Func<T, TValue>> propertySelector, IEnumerable<TValue> values)
{
return source.Where(GetWhereInExpression(propertySelector, values));
}
private static Expression<Func<T, bool>> GetWhereInExpression<T, TValue>(Expression<Func<T, TValue>> propertySelector, IEnumerable<TValue> values)
{
ParameterExpression p = propertySelector.Parameters.Single();
if (!values.Any())
return e => false;
var equals = values.Select(value => (Expression)Expression.Equal(propertySelector.Body, Expression.Constant(value, typeof(TValue))));
var body = equals.Aggregate<Expression>((accumulate, equal) => Expression.Or(accumulate, equal));
return Expression.Lambda<Func<T, bool>>(body, p);
}
答案 1 :(得分:3)
int[] productList = new int[] { 1, 2, 3, 4 };
var myProducts = from p in db.Products
where productList.Contains(p.ProductID)
select p;
答案 2 :(得分:1)
这是SQL中查询的精确表示。
int [] productList = new int [] {1,2,3};
var myProducts = from p in db.Products
where productList.Contains(p.ProductID)
select p;
如果是实体,你能更好地描述问题吗?
确切的SQL表示将是......
SELECT [t0].[ProductID], [t0].[Name], [t0].[ProductNumber], [t0].[MakeFlag], [t0].[FinishedGoodsFlag],
[t0].[Color], [t0].[SafetyStockLevel], [t0].[ReorderPoint], [t0].[StandardCost], [t0].[ListPrice],
[t0].[Size], [t0].[SizeUnitMeasureCode], [t0].[WeightUnitMeasureCode], [t0].[Weight], [t0].[DaysToManufacture],
[t0].[ProductLine], [t0].[Class], [t0].[Style], [t0].[ProductSubcategoryID], [t0].[ProductModelID],
[t0].[SellStartDate], [t0].[SellEndDate], [t0].[DiscontinuedDate], [t0].[rowguid], [t0].[ModifiedDate]
FROM [Production].[Product] AS [t0]
WHERE [t0].[ProductID] IN (@p0, @p1, @p2, @p3)