简体   繁体   中英

Linq to SQL issue with where clause

I am trying to create a where clause in Linq to SQL using the following logic

if @supplierid is null return all records.

if @supplierid is not null return where supplierid is equals to @supplierid.

and the one that is creating an issue:

if @supplierid ==0 return all records where supplierid is null

I tried writing this like

var answers =
            from thisChargeableService in this.GetAll()
            where
            (
                (
                    (supplierId == null) ||
                    (
                        ((supplierId < 1) && (thisChargeableService.SupplierId == null)) ||
                        ((supplierId != null) && (thisChargeableService.SupplierId == supplierId.Value))
                    )
                ));

This works with the first two conditions but when @supplierid = 0, nothing is returned.

Any help with this would be much appreciated

edit

Basically I have a dropdown of N/A with an id of 0. I have used this to identify that an option has been selected from dropdown and the user is targeting all rows where the supplier id is N/A.

The database contains no entries with 0 as the supplierid, so instead I am trying to target this with where the supplierid is null or the below in SQL

    SELECT * FROM ChargeableService
WHERE 
(@supplierid is null)
OR
(
(@supplierid is not null and supplierid = @supplierid) or
(@supplierid = 0 AND supplierid is null)
)

I've taken your query and run it against some similar data and the following works:

var answers =
        from thisChargeableService in this.GetAll()
        where
        (
            supplierId == null ||
            (supplierId == 0 && thisChargeableService.SupplierId == null) ||
            (supplierId > 0 && thisChargeableService.SupplierId == supplierId)
        )
        select thisChargeableService;

With Linq, there is no need to try to build one query to do all. Instead you can build your expression in buts and let deferred execution build and execute the correct sql.

So, this is the way I would do it.

  var answers =  this.GetAll().AsQueryable();

  if (supplierId.HasValue && (supplierId.Value != 0))
     answers = answers.Where(a=>a.SupplierId == supplierId.Value);

  if (supplierId.HasValue && (supplierId.Value == 0))
     answers = answers.Where(a=>!a.SupplierId.HasValue);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM