This is a migrated thread and some comments may be shown as answers.

Using Linq.Any() in a ternary, cause a sql bug

3 Answers 106 Views
Feature Requests
This is a migrated thread and some comments may be shown as answers.
This question is locked. New answers and comments are not allowed.
Lagrange
Top achievements
Rank 1
Lagrange asked on 23 Oct 2015, 12:56 AM

Hi,

 I have an issue using a .Where() statement containing a ternary.

Each path of the ternary return the evaluation to execute.

FluentModel.Accounts.Where(a =>
a.AccountType == 1 ? a.Business == _idBusiness // for directs seller, check direct business
: a.AccountType ==2 ? a.Customers.Any(c => c.Business == _idBusiness) // for indirect seller, check their client business
: false
);

This generate an invalid statement, at least on sql serveur :

1....
2.CASE WHEN a.[​Business] = 2
3.                THEN EXISTS(SELECT 1 FROM ​ ....)
4.                ELSE
5....

The correct expression should be :

1....
2.CASE WHEN a.[​Business] = 2
3.                THEN CASE WHEN EXISTS(SELECT 1 FROM ​ ....)
4.                    THEN 1 ELSE 0 END
5.                ELSE
6....

 

I'm using the 2015.1 version of openaccess

Regards,

3 Answers, 1 is accepted

Sort by
0
Lagrange
Top achievements
Rank 1
answered on 23 Oct 2015, 01:17 AM

I've a workaround by using Count() > 0 instead of Any(), which produce a valid query.

But now, I see another problem in the query :

the generated ​query contains a JOIN to the Customers table, instead of a LEFT JOIN, so all account of type 1 who don't have customers, will not be in the resultset.

0
Thomas
Telerik team
answered on 27 Oct 2015, 06:58 PM
I would propose to use something along these lines:


FluentModel.Accounts.Where(a =>
(a.AccountType == 1 && a.Business == _idBusiness) // for directs seller, check direct business
|| (a.AccountType == 2 && a.Customers.Any(c => c.Business == _idBusiness)) // for indirect seller, check their client business
);

Using the ternary operator looks good in c#, but is not the way to go with SQL. Don't do to much in
its branches!

Regards,
Thomas
Telerik
 
Check out the latest announcement about Telerik Data Access vNext as a powerful framework able to solve core development problems.

 
0
Lagrange
Top achievements
Rank 1
answered on 27 Oct 2015, 10:45 PM

I simplified the model ​to provide an understandable repro. Real world is far more complicated with 4 successives conditions.

Anyway, I've throw away the linq approach for this query, and written a custom sql to get the int[] rows id I want, then I get fluent objects using .Where(a => ​result.Contains(a.AccountId))

 

Thanks for help. This post was mainly to inform you about this sql syntax bug.

Tags
Feature Requests
Asked by
Lagrange
Top achievements
Rank 1
Answers by
Lagrange
Top achievements
Rank 1
Thomas
Telerik team
Share this question
or