[英]ASP.NET MVC: Is it a good practice to check existence of a Linq Object in database by exception handling?
在我的ASP.NET MVC应用程序中,当我要获取一个项目时,通常会使用Any()
检查其存在,然后通过.Single()
来获取该项目。 但是我想到减少数据库查询的数量,我尝试使用这种结构:
item myItem = null;
try
{
myItem = (from item in dbContext.items
where item.id == itemID
select item).Single();
}
catch (Exception e)
{
// i understand item is not exist in db
}
// if item is available
if (myItem ==null){
//item was not in db
}else{
//item is present id db
}
它只提取一次数据库,如果项目不存在,它将抛出异常,因此我不再需要检查Any()
结果。 这是提高我的应用程序效率还是由于异常处理而导致某些性能下降?
不它不是。 为什么不使用SingleOrDefault()
。 这样一来,您就无需针对这种情况进行异常处理,并且代码的其余部分可以保持不变。
如果您认为会有一个值或可能为null,请使用SingleOrDefault
:
myItem = (from item in dbContext.items
where item.id == itemID
select item).SingleOrDefault();
然后检查一下:
// if item is available
if (myItem ==null){
//item was not in db
}else{
//item is present id db
}
如其他答案所述,最好使用.SingleOrDefault(),如果使用的是C#6,则可以使用空条件运算符来简化表达式。
myItem = (from item in dbContext.items
where item.id == itemID
select item).SingleOrDefault();
var somePropertyValue = myItem?.SomeProperty;
myItem?.SomeProperty将返回属性的值;如果myItem为null,则返回null。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.