Much of the time, it's fairly straightforward to express an SQL query in Linq instead. However, there are some things that aren't quite so clear how to do. In this article, I'll take a look at some of those.
LIKE
There are a couple of ways to replace LIKE. If you just want to directly use LIKE, then you can do so using the SqlMethods class. To use this, you must add the following using declaration at the top of the file:
using System.Data.Linq.SqlClient;
Then we can use it like this:
var Result = from Book in DB.BookResources
where SqlMethods.Like(Book.Title, "%java%")
select Book;
This will create an SQL query that locates all books containing "java" (case-insensitively). Interestingly, you can also do the following:
var Result = from Book in DB.BookResources
where Book.Title.Contains("java")
select Book;...
Writing automated tests is a tried and tested way to improve the quality of software. In the initial phase of development, tests help to verify that the code functions correctly. In Test Driven Development, tests are written before the code, so any knowledge about the ins and outs of the implementation won't influence the writing of the tests. After the initial development, as changes are made over time, a comprehensive test suite can quickly point out unintended changes in the behavior of the code, so the bugs can be fixed before the software is shipped. Importantly, the tests are automated, so they are very cheap to run in terms of time.
What do we want from a test suite?
There are a range of properties that are good to have in a test suite.
- It often allows bugs to be pinpointed to a relatively small area of the code base, saving debugging time...
It's fair to say that I'm a pretty heavy user of Linq. You'll find uses of it scattered across my code, from the obvious (using DLinq to query a database) to the slightly more exotic (writing queries over collections obtained from classes in System.Reflection). Linq often allows you to express a problem very neatly, resulting in compact, readable code. It also factors out the application of operations and leaves you to worry about the operations themselves, likely decreasing bugs.
Fixing A Bug
Today I ran across some code that took a parameter, then used it in a Linq query. Omitting the clutter, it looked something like this:
public void Lookup(string URL, ref int ID, ref int Status)
{
// ...stuff...
var Result = from D in DB.Datas
where D.URL == URL
select D;
// ...more stuff...
}...