在 linq to sql 中我可以这样做:

var q = db.Colors;
if(! string.IsNullOrEmpty(colorName))
   q = q.Where(c=>c.Name.Equals(colorName));
return q.ToList();

在 Db4O linq 中我不能这样做,因为我必须从

var q = (from Color c in db
         select c);
if(! string.IsNullOrEmpty(colorName))
   q = q.Where(c=>c.Name.Equals(colorName));
return q.ToList();

这导致

  1. 所有颜色的完整枚举
  2. 按名称过滤。

这当然不是我想要的解决方案。有什么建议么?

有帮助吗?

解决方案

这样的事情合适吗?

return (from Color c in db
       where !String.IsNullOrEmpty(colorName) && c.Name.Equals(colorName)
       select c).ToList();

然后您还可以使用多个参数:

return (from Color c in db
       where (!String.IsNullOrEmpty(colorName) && c.Name.Equals(colorName))
          || (!String.IsNullOrEmpty(color1Name) && c.Name.Equals(color1Name))
          || (!String.IsNullOrEmpty(color2Name) && c.Name.Equals(color2Name))
          ...
       select c).ToList();

其他提示

我不确定你在说什么。您是否担心在第一种情况下,某些代码会在服务器端执行,以便您优化返回的值。但在第二种情况下,枚举是在本地完成的,因此对使用的值没有优化?

如果是这样,则 LINQ to Objects 无法避免这种情况。这些对象位于内存中,因此无法避免枚举它们来执行过滤操作。

如果拆分表达式会怎样:

IDb4oLinqQuery<Color> q;
if(! string.IsNullOrEmpty(colorName))
{
  q = from Color c in db
      where c.Name.Equals(colorName)
      select c;
}
else
{
  q = from Color c in db
      select c;
}
return q.ToList();

这样 Db4O 预处理器就会看到 2 个不同的 LINQ 查询?缺点当然是这个解决方案更加冗长而且不完全是DRY..

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top