我从数据库中查询数据以显示在我的视图中。我使用了这个查询:
var ien_content = from c in this.DataContext.tbl_Contents
where c.ContentTypeID == id
&&
(
IsActive == false?true :(c.Active == null?true:c.Active > 0)
)
orderby c.RegisterDate descending
select c;
return ien_content.ToList();
在这个tbl_Contents中有许多行,但是当所有这些行都被设置为Active = 0时,它显示错误:System。NullReferenceException:对象引用没有设置为对象的实例。
谁能告诉我,如何捕获这个错误?谢谢。
使用where c!= null condition。因此,您可以这样重写它:
if(DataContext != null && DataContext.tbl_Contents != null)
{
var ien_content = from c in this.DataContext.tbl_Contents
where c!= null && c.ContentTypeID == id
&&
(
IsActive == false?true :(c.Active == null?true:c.Active > 0)
)
orderby c.RegisterDate descending
select c;
}
如果仍然存在异常,那么只剩下c.RegisterDate可以为空。检查c。registerdate是否对任何行都不为空。
试着用forloop替换linq,这样你就可以逐行调试了,就像这样
List list = new List();
foreach(var c in this.DataContext.tbl_Contents)
{
if(c.ContentTypeID == id && ( IsActive == false?true :(c.Active == null?true:c.Active > 0)))
list.Add(c)
}
根据您提供的有限信息,我猜c
本身是空的。您确定tbl_Contents
中没有null
行吗?
首先试着不使用isActive line:
var ien_content = from c in this.DataContext.tbl_Contents
where c.ContentTypeID == id
orderby c.RegisterDate descending
select c;
if(ien_content.Count() > 0 )
{
//records exist
}
else {//no records}
如果没有问题:
var ien_content = from c in this.DataContext.tbl_Contents
where c.ContentTypeID == id
&& (IsActive == false?true :(c.Active == null?true:Convert.ToInt32(c.Active) > 0))
orderby c.RegisterDate descending
select c;
if(ien_content.Count() > 0 )
{
return ien_content.ToList();
}
else {//no records}
或者你可以在linq方法中单独使用IsActive。
if(IsActive==true)
{
var ien_content = from c in this.DataContext.tbl_Contents
where c.ContentTypeID == id
&& c.Active == null
orderby c.RegisterDate descending
select c;
if(ien_content.Count() > 0 )
{
return ien_content.ToList();
}
else {//no records}
}
else
{
var ien_content = from c in this.DataContext.tbl_Contents
where c.ContentTypeID == id
&& Convert.ToInt32(c.Active) > 0
orderby c.RegisterDate descending
select c;
if(ien_content.Count() > 0 )
{
return ien_content.ToList();
}
else {//no records}
}
对