3

I'm trying to write a single query which will include one of the two conditions, based on an input variable:

!(from o in db.Products.Where(x => x.Company_ID == cid && x.IsDeleted != true)

or

(from o in db.Products.Where(x => x.Company_ID == cid && x.IsDeleted != true)

My current method, covering the former condition, is as follows. I have included productExists, which will be the parameter which determines whether I want condition #1 or #2 from above.

public IQueryable<ProductImportViewModel> AllImports(int id, bool productExists)
{
    return (from t1 in db.Products_Staging
            where (t1.ImportFileId == id) && !(from o in db.Products.Where(x => x.Company_ID == cid && x.IsDeleted != true)
                                               select o.ProductName).Contains(t1.ProductName)
            select new ProductImportViewModel
            {
                Id = t1.Id
            }
}

If anybody could help me with this, I'd be much appreciated.

1 Answer 1

2

Something like this maybe:

where (t1.ImportFileId == id) && 
            (
                productExists==true
                &&
                !(from o in db.Products.Where(x => x.Company_ID == cid && x.IsDeleted != true).
                                                Select(o=> o.ProductName).Contains(t1.ProductName)
            )
            ||
            (
                productExists==false
                &&
                (from o in db.Products.Where(x => x.Company_ID == cid && x.IsDeleted != true).
                                                Select(o=> o.ProductName).Contains(t1.ProductName)
            )

You could also do it something like this:

var query=(from o in db.Products
          .Where(x => x.Company_ID == cid && x.IsDeleted != true).
          Select(o=> o.ProductName);
------
where (t1.ImportFileId == id) && 
    (
        productExists && !query.Contains(t1.ProductName)
    )
    ||
    (
        !productExists && query.Contains(t1.ProductName)
    )

Both queries will result in the same sql

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. That's pretty much what I did. I just wondered if there was a more succinct way to do it!

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.