Sunday, November 18, 2012

Using LinQ in C#

LINQ is actually a pretty cool technology; it allows you to do something like list or monad comprehensions over collections, but with a sql-like syntax; better yet, it does magic so you can use SQL tables instead of collections, and it actually generates and sends the SQL to the DBMS, instead of getting all the data into memory and iterating over it.
Since I switch languages constantly, I'm always trying to remember the right syntax; so, this is my place to have it, for now. Before you can connect to your DB, you need to run a VS tool, that will generate the LINQ for your particular schema (and you need to rerun every time you change :( . In my case, the generated code is in the SimpleBlog package, and the generated class is SimpleBlogDataContext; so my code for reading something looks like:
And to add an element to the blog table, we can do:

Notice that the context (ctx here) needs to be a global variable; having several contexts will diminish performance and probably confuse you, since variables from one context cannot be saved in another.

We always need to import the System.Linq namespace when using linq; If we're doing this directly in an aspx page we use an import directive, like: Notice that you need to add an assembly reference (at least in VS2008, you need to add it to the web.config file, even if you add it to the project references in solution explorer), so add the following line to your web.config, inside the <assemblies> tag:  <add assembly="System.Data.Linq, Version=, Culture=neutral, PublicKeyToken=b77a5c561934e089" />

1 comment: