How to construct a proper WHERE clause with RavenDb

旧时模样 提交于 2019-12-23 04:19:31

问题


I have experimented with 2 forms of the call, this one

 products = DocumentSession.Query<Product>()
      .Statistics(out stats)
      .Where(p => p.INFO2.StartsWith(term1))
      .Where(p => p.INFO2.StartsWith(term2))
      .Where(p => p.INFO2.StartsWith(term3)) 
      .OrderByField(columnToSortBy, columnToSortByAsc)
      .Skip(pageIndex * pageSize)
      .Take(pageSize)
      .ToList()
      ;

and this way

  products = DocumentSession.Query<Product>()
      .Statistics(out stats)
      .Where(p => p.INFO2.StartsWith(term1) & p.INFO2.StartsWith(term2) & p.INFO2.StartsWith(term3))
      .OrderByField(columnToSortBy, columnToSortByAsc)
      .Skip(pageIndex * pageSize)
      .Take(pageSize)
      .ToList()
      ;

The first one returns records that are more in-line with my expectations, while the seconds seems to return ALL documents of type Product. What are the differences between the 2 from a LINQ expression point of view, and have I overlooked anything that might negate what I am trying to accomplish, which is a 3 term query and each term being AND'd together.

EDIT: revised code per Russ.

  string t1 = terms[0];
  string t2 = terms[1];
  string t3 = terms[2];

  products = DocumentSession.Query<Product>()
      .Statistics(out stats)
      .Where(p => p.INFO2.StartsWith(t1) && p.INFO2.StartsWith(t2) && p.INFO2.StartsWith(t3)) 
      .OrderByField(columnToSortBy, columnToSortByAsc)
      .Skip(pageIndex * pageSize)
      .Take(pageSize)
      .ToList()
      ;

EDIT 2: This is where you smash your face down on the keyboard, or any other solid object for that matter... Gotta get back to the basic here with standard C# And and Or

Thank you, Stephen


回答1:


In the second block you're doing an & instead of an && so instead of being an AND comparison, it's trying to do a bitwise operation.

Edit: in the 2nd case, you can change this:

.Where(p => p.INFO2.StartsWith(terms[0]) & p.INFO2.StartsWith(terms[1]) & p.INFO2.StartsWith(terms[2]))

to this:

.Where(p => p.INFO2.StartsWith(terms[0]) && p.INFO2.StartsWith(terms[1]) && p.INFO2.StartsWith(terms[2]))

Which makes it proper AND clause.

2nd edit: If this is meant to be an AND operation, then you don't need 3 terms - you need a single term, otherwise you'll be comparing against 3 instances of the same string.

terms[0] = "test";
terms[1] = "test";
terms[2] = "test";

.Where(p => p.INFO2.StartsWith(terms[0]) && p.INFO2.StartsWith(terms[1]) && p.INFO2.StartsWith(terms[2]))

Is the same as

string term = "test";

.Where(p => p.INFO2.StartsWith(term) && p.INFO2.StartsWith(term) && p.INFO2.StartsWith(term))

Just mentioning this as this may make your code harder to maintain in the future.



来源:https://stackoverflow.com/questions/10003360/how-to-construct-a-proper-where-clause-with-ravendb

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!