August 17, 2014

LINQ to SqlServer

  • Create new project.
  • Add the linq2db.SqlServer nuget to the project.
  • Copy the LinqToDB.Templates\CopyMe.SqlServer.tt.txt to a folder where you would like to generate your data model, rename it, and delete .txt extension.
  • Modify the connection settings in the T4 template to connect to your database.
    <#@ template language="C#" debug="True" hostSpecific="True"                           #>
    <#@ output extension=".generated.cs"                                                  #>
    <#@ include file="$(ProjectDir)LinqToDB.Templates\LinqToDB.SqlServer.Tools.ttinclude" #>
    <#@ include file="$(ProjectDir)LinqToDB.Templates\PluralizationService.ttinclude"     #>
    <#
        NamespaceName = "DataModel";
    
        LoadSqlServerMetadata(@"DBHost\SqlServer2012", "Northwind", "sa", "TestPassword");
        GenerateModel();
    #>
    
  • Add connection string to the web/app.config file:
    <?xml version="1.0" encoding="utf-8" ?>
    <configuration>
        <connectionStrings>
            <add name="Northwind" providerName="System.Data.SqlClient"
                connectionString="Data Source=DBHost\SqlServer2012;Database=Northwind;User Id=sa;Password=TestPassword;" />
        </connectionStrings>
    </configuration>
    
  • To access your database use the following code:
    using System;
    using System.Diagnostics;
    using System.Linq;
    
    using DataModel;
    
    using LinqToDB.Data;
    
    namespace LinqToDBDemo
    {
        // Watch video on http://youtu.be/Qc-5UpMYQO0
        //
        class Program
        {
            static void Main(string[] args)
            {
    #if DEBUG
                DataConnection.TurnTraceSwitchOn();
                DataConnection.WriteTraceLine = (s, s1) => Debug.WriteLine(s, s1);
    #endif
    
                using (var db = new NorthwindDB())
                {
                    var q =
                        from c in db.Customers
                        select new
                        {
                            c.CompanyName,
                            OrderCount = c.Orders.Count()
                        };
    
                    foreach (var c in q)
                        Console.WriteLine(c);
                }
            }
        }
    }