taii el mehdi
taii el mehdi

Reputation: 41

How to use and if statement in linq Entity framework c#

I am declaring this variable to get data from my database(example)

var products = _context.Products();

and I need to use like this example

if(ctId == -1)
{
    // get project list 
    var products = _context.Products().where(a => a.categoryId == 2);
}
else
{
    //get category list
    var products = _context.Products().where(a => a.categoryId == 1);
}

but my problem how to declare var products to using like this

if(ctId == -1)
{
    // get project list 
    products = _context.Products().where(a => a.categoryId == 2);
}
else
{
    //get category list
    products = _context.Products().where(a => a.categoryId == 1);
}

Upvotes: 1

Views: 136

Answers (1)

TheGeneral
TheGeneral

Reputation: 81493

To the initial problem, you would declare an IQueryable<Product> outside the if scope

IQueryable<Product> products = null;

if(ctId == -1)
   products = _context.Products().where(a => a.categoryId == 2);
else
   products = _context.Products().where(a => a.categoryId == 1);

However, you could also use a ternary conditional operator

The conditional operator ?:, also known as the ternary conditional operator, evaluates a Boolean expression and returns the result of one of the two expressions, depending on whether the Boolean expression evaluates to true or false.

The syntax for the conditional operator is as follows:

condition ? consequent : alternative

Example

var id = ctId == -1 ? 2 : 1;
var products = _context.Products().where(a => a.categoryId == id);

or potentially

var products = _context.Products().where(a => a.categoryId == (ctId == -1 ? 2 : 1));

Upvotes: 5

Related Questions