代码之家  ›  专栏  ›  技术社区  ›  Paulo Santos

如何一次查询多个实体?

  •  3
  • Paulo Santos  · 技术社区  · 16 年前

    我正在尝试查询一个实体,以根据筛选器返回多行。

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

    在LINQ to实体中如何执行此操作?

    3 回复  |  直到 16 年前
        1
  •  4
  •   Paulo Santos    16 年前

    虽然我确实收到了一些及时的答复,我为此感谢大家。我收到的回复中显示的方法不起作用。

    我不得不不断地寻找,直到我最终找到了一种方法来做我需要的事情 Microsoft Forums .

    简而言之,它的扩展方法如下:

        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);
        }
    
        2
  •  3
  •   Galwegian    16 年前

    int[] productList = new int[] { 1, 2, 3, 4 };
    
    var myProducts = from p in db.Products
                     where productList.Contains(p.ProductID)
                    select p;
    
        3
  •  1
  •   irperez    16 年前

    这是SQL中查询的精确表示形式。

    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)