假设我有两个实体:
public class Animal {
public int ID { get; set; }
public string Name { get; set; }
public bool EatsVegetables { get; set; }
public bool EatsMeat { get; get; }
public bool EatsFruits { get; set; }
}
public bool Food {
public int ID { get; set; }
public string Name { get; set; }
public bool ContainsVegetables { get; set; }
public bool ContainsMeat { get; get; }
public bool ContainsFruits { get; set; }
}
(我们认为这些动物可以吃任何不含它们不能吃的东西的东西。)现在给定一种特定的食物,我想找出我可以喂给哪些动物,并且给定一种特定的动物,我想知道我可以喂它什么。
public static Expression<Func<Animal, IEnumerable<Food>>> GetAllowedFoods(MyDataContext db) {
return a => db.Foods.Where(f =>
(a.EatsVegetables || !f.ContainsVegetables)
&& (a.EatsMeat || !f.ContainsMeat)
&& (a.EatsFruits || !f.ContainsFruits));
}
相反的表达式看起来非常相似:
public static Expression<Func<Food, IEnumerable<Animal>>> GetAllowedAnimals(MyDataContext db) {
return f => db.Animals.Where(a =>
(a.EatsVegetables || !f.ContainsVegetables)
&& (a.EatsMeat || !f.ContainsMeat)
&& (a.EatsFruits || !f.ContainsFruits));
}
所以真正有意义的是一个组合表达式:
public static Expression<Func<Animal, Food, bool>> IsAllowedDiet() {
return (a, f) =>
(a.EatsVegetables || !f.ContainsVegetables)
&& (a.EatsMeat || !f.ContainsMeat)
&& (a.EatsFruits || !f.ContainsFruits));
}
不知何故,上面的两种方法,GetAllowedFoods
应该GetAllowedAnimals
调用表达式IsAllowedDiet
。
我认为这是LinqKit应该能够立即完成的事情,但作为 LinqKit 的初学者,我不知道正确的语法是什么!