C# 如果int为null并接受all,如何创建请求
如何在没有很多条件的情况下提出正确的请求 如果字符串可以为null,我可以使用C# 如果int为null并接受all,如何创建请求,c#,entity-framework-core,C#,Entity Framework Core,如何在没有很多条件的情况下提出正确的请求 如果字符串可以为null,我可以使用someString.Contains(null??string.Empty) 我的请求是全部的,但是如果我的int为null,如何获取全部呢?我不想赚太多的钱 var students = _context.Students.Where(x => x.FacultetId == Facultet &&
someString.Contains(null??string.Empty)
我的请求是全部的,但是如果我的int为null,如何获取全部呢?我不想赚太多的钱
var students = _context.Students.Where(x =>
x.FacultetId == Facultet &&
x.Profession.Contains(model.Profession ?? string.Empty) &&
x.City.Contains(model.City ?? string.Empty) &&
x.Course == model.Course &&
x.Specialization.Contains(model.Specialization ?? string.Empty
)
).ToList();
与其在查询中设置这么多条件,不如在外部执行:
var query = _context.Students.Where(x => x.FacultetId == Facultet);
// filter by profession if there is some value
if (!string.IsNullOrempty(model.Profession))
{
query = query.Where(x => x.Profession.Contains(model.Profession));
}
// continue with the rest of the filters...
// and only then execute the query
var students = query.ToList();
检查可为空的int
也是一样的
假设SomeValue
为
public int? SomeValue;
然后:
“但是,如果我的int为null,该如何处理?”\n上下文中的int字段首先可以为null吗?如果它是一个可为null的int,那么您可以执行相同的“?”技巧。
someString.Contains(null??string.Empty)
相当于编写someString.Contains(string.Empty)
。我不认为您完全理解null合并运算符(??
)的作用。但是我想在方法中使用all if int nullin来获取1中带有null1000请求的值second@Adilbek这有什么关系?在.NET中执行if
要比在SQL中执行WHERE
快得多如果这不重要,那么我将使用您的答案
if (model.SomeValue != null)
{
query = query.Where(x => x.SomeValue == model.SomeValue);
}