开发者

omit nullable types in linq-sql query

开发者 https://www.devze.com 2022-12-19 06:45 出处:网络
I have some code like this trying to get some data from a Documents table based on some filters passed in (ContentRef and TypeRef)...

I have some code like this trying to get some data from a Documents table based on some filters passed in (ContentRef and TypeRef)...

 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;
            }

if either ContentRef or TypeRef are null then i dont want it to do a check for if its null i just want it ignored.

eg if both are null my method should return the equiavalent of

 return from document in db.Documents
       开发者_开发知识库                where document.IsArchived == archived
                       select document;

how can i do this?


Try this:

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;
}

When ContentRef is null, the document.ContentRef == ContentRef part will not be evaluated.


With deferred execution, you can construct your query like this because the execution only occurs when GetEnumerator is called.

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;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消