2010-02-01 77 views
1

我有一些这样的代码试图从基于一些过滤器(ContentRef和TypeRef)通过一个文件表中获取的一些数据...在LINQ-SQL查询忽略空类型

public IQueryable<Document> GetFilteredDocuments(bool archived, int? ContentRef, int? TypeRef) 
      { 
       return from document in db.Documents 
         where document.IsArchived == archived 
         && (document.ContentRef == ContentRef) 
         && (document.TypeRef == TypeRef) 
         select document; 
      } 

如果任ContentRef或TypeRef为空,那么我不希望它做一个检查,如果它的空我只是想让它忽略。

例如,如果都为null我的方法应该返回的

return from document in db.Documents 
         where document.IsArchived == archived 
         select document; 

的equiavalent我怎么能做到这一点?

回答

0

试试这个:

public IQueryable<Document> GetFilteredDocuments(bool archived, int? ContentRef, int? TypeRef) 
{ 
    return from document in db.Documents 
      where document.IsArchived == archived 
      && (ContentRef == null || document.ContentRef == ContentRef) 
      && (TypeRef == null || document.TypeRef == TypeRef) 
      select document; 
} 

当ContentRef为空,则document.ContentRef == ContentRef部分将不进行评估。

0

随着推迟执行,您可以像这样构造您的查询,因为执行只发生在调用GetEnumerator时。

public IQueryable<Document> GetFilteredDocuments(bool archived, int? ContentRef, int? TypeRef) 
{ 
    IQueriable<Document> docs = db.Documents.Where(d => d.IsArchived == archived); 
    if (ContentRef != null) 
     docs = docs.Where(d => d.ContentRef == ContentRef); 
    if (TypeRef != null) 
     docs = docs.Where(d => d.TypeRef == TypeRef); 
    return docs; 
}