我想要从中返回查询
WANOM_DETAILS & STRDT tables where PIPELINE = 'F' AND HISTORICAL_FLAG <> 'T' AND INSTALLATION = 'EA' AND ANOMALY_CLASS = 'Critical'
。
if语句正常工作,但目前只返回查询
WANOM_DETAILS & STRDT tables where ANOMALY_CLASS = 'Critical'
因为这是model.ToList();
非常感谢任何帮助。这是代码;
strdt = "EA";
anom_class = "Critical";
var models = db.WANOM_DETAILS;
var model = models.Where(wanom_details => wanom_details.STRDT.PIPELINE == "F");
model = models.Where(wanom_details => wanom_details.STRDT.HISTORICAL_FLAG != "T");
if (strdt != "")
{
model = models.Where(wanom_details => wanom_details.INSTALLATION == strdt);
}
if (anom_class != "")
{
model = models.Where(wanom_details => wanom_details.ANOMALY_CLASS == anom_class);
}
if (subdt != "")
{
model = models.Where(wanom_details => wanom_details.WANOM.SUBSTRUCTURE == subdt);
}
if (comp != "")
{
model = models.Where(wanom_details => wanom_details.WANOM.TYPE + "-" + wanom_details.WANOM.IDENT == comp);
}
return PartialView("_SiteAnomalyGridViewPartial", model.ToList());
答案 0 :(得分:0)
你可以将Where的结果链接起来,所以:
X.Where(x => x.Prop > 1 && x.Prop2 == "1")
你可以实现两个Where的相同结果连接:
X.Where(x => x.Prop > 1).Where(x.Prop2 == "1").
所以在你的情况下你可以这样做:
strdt = "EA";
anom_class = "Critical";
var models = db.WANOM_DETAILS;
models = models.Where(wanom_details => wanom_details.STRDT.PIPELINE == "F");
models = models.Where(wanom_details => wanom_details.STRDT.HISTORICAL_FLAG != "T");
if (strdt != "")
{
models = models.Where(wanom_details => wanom_details.INSTALLATION == strdt);
}
if (anom_class != "")
{
models = models.Where(wanom_details => wanom_details.ANOMALY_CLASS == anom_class);
}
if (subdt != "")
{
models = models.Where(wanom_details => wanom_details.WANOM.SUBSTRUCTURE == subdt);
}
if (comp != "")
{
models = models.Where(wanom_details => wanom_details.WANOM.TYPE + "-" + wanom_details.WANOM.IDENT == comp);
}
return PartialView("_SiteAnomalyGridViewPartial", models.ToList());
当你使用一个长Where
表达式链接条件与&&
运算符时,sql generetd根据条件And
生成。
但是,当您使用IQueryable
表达式链接Where
时,linq-to-sql
genereate会为每个表达式选择where-where,并将所有内容包装在Union查询中。
db-server可能会优化,但对我来说这感觉很尴尬。
要获得第一个结果,您可以使用greate predicatebuilder扩展方法:
strdt = "EA";
anom_class = "Critical";
var predicate = PredicateBuilder.False<ClassOfWANOM_DETAILS>();
predicate.And(wanom_details => wanom_details.STRDT.PIPELINE == "F");
predicate.And(wanom_details => wanom_details.STRDT.HISTORICAL_FLAG != "T");
if (strdt != "")
predicate.And(wanom_details => wanom_details.INSTALLATION == strdt);
if (anom_class != "")
predicate.And(wanom_details => wanom_details.ANOMALY_CLASS == anom_class);
if (subdt != "")
predicate.And(wanom_details => wanom_details.WANOM.SUBSTRUCTURE == subdt);
if (comp != "")
predicate.And(wanom_details => wanom_details.WANOM.TYPE + "-" + wanom_details.WANOM.IDENT == comp);
return PartialView("_SiteAnomalyGridViewPartial", db.WANOM_DETAILS.Where(predicate).ToList());