Tuesday 15 July 2014

Linq.NHibernate problem with OR statement -


Note: all the code is written on top of my head, it may contain some errors, just get the full point of this question)

Define this class: (for simplicity less)

  public class coded value {public string code {get; Set; } Public string value {get; Set; }}  

Take Thousand Objects:

  coded value cv1 = new coded value () {code = "A", value = "1"}; Coded value cv 2 = new coded value () {code = "b", value = "2"}; IList & LT; CodedValue & gt; CVList = new list & lt; Coded value & gt; (); CvList.Add (CV1); CvList.Add (CV2);  

The CVList has a list of values ​​coded to filter.

Let's get into my database thesus records:

  code VALUE A1A2B1b2  

Now, I want to retrieve all the objects where the coded value is in the list

  list of var filter = myRepository () where cvList.Contains (o coded value) select o;  

Translate NHibernate this Linq to:

  Select [field ...] from [table ...] where in the code ('A '' B ') and value (' 1 ',' 2 ');  

This is incorrect if you take a look at your record example, then this SQL will return all the rows. The translation of SQL should be:

  select [field ...] from [table ...] where (code = 'a' and value = '1') or (code = 'b' 'And value =' 2 ');  

So, can I get the results, which I want to use Linq? if so, how? If not, how can I get it?

Thanks

OK, here's the solution!

I am using PredicateBuilder from this website:

Again, I create predictions:

  var expr = Predicatebuilder.False & Lt; Audit & gt; (); Foreign currency (value coded value coded in Audit IDs) {coded value cv = coded value; Expr = expr.Or (a => (a.EventId.Code == cv.Code) and (AAITID.Code systemname == cv.CodeSystemName)); } ItemQuery = itemQuery.Where (expr); The   

line coded value cv = codedValue in the foreach statement is very important, except for the line the correct SQL syntax will be created, but the value of the parameter All will be the same.

I really hope this will help someone.


No comments:

Post a Comment