Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

c# - How can I make this LINQ to SQL where clause with conditions faster?

I have the following LINQ to SQL query but I want to know if there is a faster way to validate data from a post action before adding them in a where clause? ex:

bookFilter = Informations coming from the post action

int count = from b in _libraryContext.Book
            join ba in _libraryContext.BookAuthor
            on b.Id equals ba.BookId
            where (!string.IsNullOrWhiteSpace(bookFilter.Name) ? 
            b.Name.Contains(bookFilter.Name.ToUpper()) : 1 == 1 )
            where (!string.IsNullOrWhiteSpace(bookFilter.Decription) ? 
            b.Description.Contains(bookFilter.Description.ToUpper()) : 1 == 1)
            where (bookFilter.BookId > 0 ? ba.BookId == bookFilter.BookId : 1 == 1)

return count;
question from:https://stackoverflow.com/questions/65891994/how-can-i-make-this-linq-to-sql-where-clause-with-conditions-faster

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

1 Answer

0 votes
by (71.8m points)

I've never used this type of syntax much so I'm sure if you can do it this way, but you can certainly do it with LINQ and build up your query step by step like so:

var query = _libraryContext.Set<Book>();

if(!string.IsNullOrWhiteSpace(bookFilter.Name))
{
    query = query.Where(x => x.Name.Contains(bookFilter.Name.ToUpper()));
}

if(!string.IsNullOrWhiteSpace(bookFilter.Description))
{
    query = query.Where(x => x.Description.Contains(bookFilter.Description.ToUpper()));
}

if(bookFilter.BookId > 0)
{
    query = query.Where(x => x.BookId == bookFilter.Id);
}

return query.Count();

Note: I have omitted the JOIN here as it seems unnecessary, but you can of course do the join in this syntax too if you need it.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...