Sort by multiple fields with LINQ

A few days ago I had a small issue concerning sorting. I use LINQ to SQL to get all products from a DB table and sort them by two fields – IsFavorite (boolean) and AddedOn (datetime). Normally, one will write the following LINQ query:

However, some people prefer using the C# method-based syntax, which lets you do everything .as the SQL-based one. There is a method, called OrderByDescending() which seems to do exactly what we did in the example above.

Having that, the results I got were sorted only by the AddedOn column. I checked my code 10 times and I couldn’t find what the problem was. FInally, I found my solution – ThenByDescending() method. When you want to sort on multiple columns, the first method you should use is OrderBy (OrderByDescending) and then use ThenBy (ThenByDescending) for all other columns.

Untie the Connection String from DataContext (LINQ to SQL)

When you work with LINQ to SQL you probably want your DataContext (and all the entities) to be in its own assembly. It’s a normal decision when developing n-tier applications.

The Problem

When you create your LINQ to SQL classes file (dbml) you have two options for your database connection string:

  1. In Settings.settngs file of the corresponding assembly
  2. Hard-coded in your DataContext desginer (.designer.cs file)

Well, when you have a web application or WinForms/WPF application you definitely would like to manage your connection string from the general config file (web.config or app.config). In this situation it would be a little pain. Continue Reading…

Mapping a Stored Procedure to an Entity with Entity Framework

ADO.NET Entity Framework initially generates a 1:1 (one to one) mapping between the database schema and the conceptual schema in most of the cases. In the relational schema, the elements are composed of the tables, with the primary and foreign keys gluing the related tables together. In contrast, the Entity Types define the conceptual schema of the data. One is sure – ADO.NET Entity Framework makes it easy when it comes to work with a database. But is it sure?

Suppose you have created your entities using the Visual Studio 2008 wizard.
ADO.NET Entity Framework

Continue Reading…