How to request several objects at once?

I am trying to query Entity to return multiple rows based on a filter.

For example, in SQL we have:

SELECT * FROM table WHERE field IN (1, 2, 3)

How to do this in LINQ for Entities?

+3
source share
3 answers

Although I received some quick answers, and I thank you all for this. The method shown on the responses received does not work.

I had to keep searching until I found a way to do what I needed in a post from Frederick Walle to the Microsoft Forums .

In short, this is the extension method below:

    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);
    }
+4
source

you can do something like this:

int[] productList = new int[] { 1, 2, 3, 4 };

var myProducts = from p in db.Products
                 where productList.Contains(p.ProductID)
                select p;
+3
source

, 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)
+1

Source: https://habr.com/ru/post/1705044/


All Articles