Using LINQ to SQL with SQL Server Compact

In this
article, I will cover how to access data in SQL Server Compact
databases (.sdf file) using new development technologies such as LINQ.
LINQ is the new initiative of Microsoft to support Object-Relational
Mapping concepts and design patterns. LINQ provides a full type-safety
and compile-time checking of query expressions in order to minimize the
object-relational concepts mismatch and enables managing relational
data as objects providing an easy way to integrate data validation and
business logic rules into your application.

Getting started with the solution

The first step is open Visual Studio.NET 2008, and create a Console project (see Figure 1).

SQLServer1 Using LINQ to SQL with SQL Server Compact


Figure 1

Then
go to the installation of SQL Server Compact Edition in
$PROGRAMFILES$Microsoft SQL Compact Editionv3.5Samples and copy the
Northwind.sdf file into the solution directory. Let's open a Command
Windows console and change to the solution directory.

Let's call
the SQLMetal.exe command in the Program FilesMicrosoft
SDKsWindowsv6.0ABin directory in order to generate the code and
mapping for the LINQ to SQL component of the .NET framework (see Figure
2).

SQLServer2 Using LINQ to SQL with SQL Server Compact


Figure 2

Now let's add the Northwind.cs file to the solution and a reference to the System.Data.Linq.dll assembly (see Figure 3).

SQLServer3 Using LINQ to SQL with SQL Server Compact


Figure 3

And finally, the sample code is shown in Listing 1.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace LINQ_SQLCompact
{
    class Program
    {
        static void Main(string[] args)
        {
            string strConnString = "Northwind.sdf";
            Northwind dbNorthwind = new Northwind(strConnString);
 
            var query = from c in dbNorthwind.Customers
                        where c.City == "Paris"
                        select c;
 
            foreach (Customers c in query)
            {
                System.Console.WriteLine("ContactName={0}, Address={1}, City={2}",c.ContactName, c.Address, c.City);
            }
 
            System.Console.WriteLine("Press any key to finish …");
            System.Console.Read();

       }

    }

}

GD Star Rating
loading...
GD Star Rating
loading...
  • Share/Bookmark

No related posts.

Related posts brought to you by Yet Another Related Posts Plugin.

Leave a Reply