2013-06-02 43 views
3

比方說,LINQ表達式我有兩個實體:匹配一個複雜的多對許多關係

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)); 
} 

不知怎麼上述兩種方法,GetAllowedFoodsGetAllowedAnimals應調用表達式IsAllowedDiet

我認爲這是LinqKit應該能夠做到的事情,但作爲LinqKit的初學者,我不知道正確的語法會是什麼!

+0

如何使IsAllowedDiet成爲一種簡單的方法,以動物和食物爲參數,並返回一個布爾值。 – aquaraga

+0

@aquaraga - 它必須可以轉換爲SQL。因此需要一個'Expression'而不是一個簡單的'Func'。 –

回答

0

我解決了它。方法IsAllowedDiet()仍然在問題中表達。 GetAllowedFoods()GetAllowedAnimals()表示如下:

public static Expression<Func<Animal, IEnumerable<Food>>> GetAllowedFoods(MyDataContext db) { 
    var isAllowed = IsAllowedDiet(); 
    return a => db.Foods.AsExpandable().Where(f => isAllowed.Invoke(a, f)); 
} 

public static Expression<Func<Food, IEnumerable<Animal>>> GetAllowedAnimals(MyDataContext db) { 
    var isAllowed = IsAllowedDiet(); 
    return f => db.Animals.AsExpandable().Where(a => isAllowed.Invoke(a, f)); 
} 

我開始享受LinqKit! :-)