问题描述
是否可以将此 linq 语句中的 Where 条件存储在变量中?
Func<NutritionValues, bool> condition; if (isBarcode) condition = f => f.barcode == name; else condition = f => f.food == name; var foods = context.NutritionValues.Where(condition). Select(f => new SerializableFood { Name = f.food, Calories = f.energy_kcal, Carbohydrates = f.carbohydrates, Fats = f.fats, Proteins = f.protiens });
条件是 100% 正确的.如果我将条件 f => f.barcode == name 直接写入 Where 函数,它可以工作,但这种方式不行.此代码返回空集.请问,你知道为什么吗?
推荐答案
您可能正在使用 LINQ to SQL 或类似的东西.
您应该将变量更改为 Expression<Func<NutritionValues, bool>>;这将允许查询提供程序解析您的条件.
问题描述
its possible to store Where condition in this linq statement in variable?
Func<NutritionValues, bool> condition; if (isBarcode) condition = f => f.barcode == name; else condition = f => f.food == name; var foods = context.NutritionValues.Where(condition). Select(f => new SerializableFood { Name = f.food, Calories = f.energy_kcal, Carbohydrates = f.carbohydrates, Fats = f.fats, Proteins = f.protiens });
Condition is 100% right. If I write condition f => f.barcode == name directly into the Where function it works, but this way not. This code return empty set. Please, do you know why?
推荐答案
You're probably using LINQ to SQL or something similar.
You should change your variable to an Expression<Func<NutritionValues, bool>>; this will allow the query provider to parse your condition.
相关问答
相关标签/搜索