Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
237 views
in Technique[技术] by (71.8m points)

database - Filtering out null values in a linq search

Im building a book library which handles Books and Journals. I have a winform where the user enters some parameters to search on the library DB. i do not know which value he selects to insert.

For example:

public abstract class Item : IComparer, IEnumerable
{
    public string Name { get; set; }
    public string Publisher { get; set; }
    public double Price { get; set; }
    public double Discount { get; set; }
    public DateTime ReleaseDate { get; set; }
}

this is my base class. when a user can insert to search by name (which translates into book name). the UI has many options to search by, and basiclly includes almost all of the fields that a book contains.

What i need to do is filter out only the fields that the user inserted, pass them to my DAL so he can perform the search using a LINQ query on ENTITY framework mapped DB.

this is my search so far:

public List<Books> SelectBookFromDB(Item itemType)
{
    BookVO book = itemType as BookVO;
    var result = myEntities.Books.Where(x =>
                                        x.Author == book.Author &&
                                        x.Discount == book.Discount &&
                                        x.Name == book.Name &&
                                        x.Publisher == book.Publisher).ToList();              
    return result;
}

problem is, im searching for some values that may be null. that way, my searches always come up empty :( i have no clue how to proceed. would love some help.

thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use more then one step to generate the query:

var result = myEntities.Books;

if(string.IsNullOrWhiteSpace(book.Author) == false)
{
  result = result.Where(x => x.Author == book.Author);
}

if(string.IsNullOrWhiteSpace(book.Name) == false)
{
  result = result.Where(x => x.Name == book.Name);
}

...And so on.

return result;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...