0

I cannot understand what is wrong with following query:

var tmp = dbset.AsEnumerable<mytable>().Where(
c=>c.Barcode.Contains("11") && c.Description.Contains("EW") );
return tmp;

Should this be same as:

select * from mytable
where Barcode like '%11%' and Description like '%EW%';

If I run this in sql server i get four rows as it should be, but not when I run the linq query i get 0 rows.

Can please someone help me. It is rather a simple query and it is giving me such a headache. Thank you very much

3 Answers 3

3

You forget fetch data, do this:

var tmp = dbset.AsEnumerable<mytable>().Where(
c=>c.Barcode.Contains("11") && c.Description.Contains("EW") );
return tmp.ToList();

Also do not call AsEnumerable soon, use it as below:

var tmp = ctx.mytable.Where(
                  c=>c.Barcode.Contains("11") && c.Description.Contains("EW") );
return tmp.ToList();
Sign up to request clarification or add additional context in comments.

4 Comments

Also, don't think AsEnumerable will help you, because the IEnumerable itself is lazy and will return an element only when iterated over (e.g. ToList()) :)
yes tolist worked for this particular query( with AsEnumerable ). Thanks a Bunch
@VladislavZorov, but AsEnumerable fetches data.
@user875615, use my second style. first one fetches all data from server then going to process which is not good.
2
dbset.AsEnumerable<mytable>()...

Don't do that!

You are causing all your data to get pulled from the database before checking the Where condition.

Other than that, it's not really clear why your query isn't working. Your syntax is correct. I'm guessing the data doesn't actually look like you think it does. Either that, or you're expecting like %EW% to match something in a case-insensitive manner and since the Where clause is being evaluated by LINQ to Objects you're not getting that behavior.

2 Comments

Tx for the clarification. I am not actually doing that. I am using PredicateBuilder from LinqKit and it was a problem with the for loop I was using to build the expression. I just wrote that linq query to quickly test what I thought end query should look like and it didn't work. Tx for the tip, it added to my knowledge of EF
@user875615: No problem. For future reference, I'd suggest you use LINQPad to see what SQL is being generated by your queries. It's an easy way to narrow down where the problem with your query might be.
0

Run a query with only one condition? " c.Barcode.Contains("11") ".

That code should run fine.

1 Comment

Yeah I can, the problem wasn't Linq, it was with PredicateBuilder expression I was trying to generate dynamically.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.