Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/entity-framework/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何在linq实体框架c中使用和if语句#_C#_Entity Framework_Linq - Fatal编程技术网

C# 如何在linq实体框架c中使用和if语句#

C# 如何在linq实体框架c中使用和if语句#,c#,entity-framework,linq,C#,Entity Framework,Linq,我声明此变量是为了从数据库中获取数据(示例) 我需要用这个例子 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

我声明此变量是为了从数据库中获取数据(示例)

我需要用这个例子

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);
}
但是我的问题是如何声明
var产品
像这样使用

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);
}

对于初始问题,您将在
if
范围之外声明一个
IQueryable

IQueryable<Product> products = null;

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

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

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

对于初始问题,您将在
if
范围之外声明一个
IQueryable

IQueryable<Product> products = null;

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

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

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

IQueryable产品
IQueryable产品
我建议您明确表示,您可以在
if
之外添加
IQueryable产品
。我想你有点建议说“你所拥有的一切都没有错”,但我认为OP不理解这一点——因此问题就来了。我建议你明确表示,你可以在
if
之外添加
IQueryable产品。我想你是在暗示“你所拥有的一切都没有错”,但我认为OP并不理解这一点——这就是问题所在。