【发布时间】:2011-03-16 22:15:51
【问题描述】:
我目前拥有的看起来有点像这样:
if(userLikesBananas)
{
return from fruit in basket
select new Fruit
{
AteBanana = Bowl.Any(b => b.OwnedBy == user && b.Contains(fruit) && fruit.Type == FruitType.Banana),
...
...
//lots of properties
...
}
}
else
{
return from fruit in basket
select new Fruit
{
AteBanana = Bowl.Any(b => b.Contains(fruit)),
...
...
//lots of properties
...
}
}
诚然,这个例子毫无意义,但原则是我想根据任意标准更改属性选择的条件。现在重复选择语句。
现在是我需要添加另一个依赖条件的时候了。我不希望有 4 种不同的情况,属性条件略有不同。
我想做的事情是这样的:
Func<Fruit, bool> fruitFunc = f => false;
if(userLikesBananas)
{
fruitFunc = f => Bowl.Any(b => b.OwnedBy == user && b.Contains(f) && f.Type == FruitType.Banana);
}
else
{
fruitFunc = f => Bowl.Any(b => b.Contains(f));
}
return from fruit in basket
select new Fruit
{
AteBanana = fruitFunc(fruit)
...
...
//lots of properties
...
};
问题在于表达式无法转换为 sql,因为它包含动态调用。我尝试将Func 包装在Expression 中,但似乎出现了同样的问题。
那么问题来了,如何避免复制粘贴呢?
【问题讨论】:
标签: c# linq linq-to-sql dynamic