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);
                }
            }
        }
    }
    

August 26, 2013

LINQ to DB. Introduction.

LINQ to DB is a database LINQ provider that allows you working with your database using an application object model.

In addition to basic LINQ query operations, LINQ to DB also introduces DML and DDL extensions such as Insert, Delete, Update, CreateTable, DropTable, etc. methods.

Why LINQ to DB

Comparing to other database LINQ providers, LINQ to DB is not a typical ORM that supports entity services such as automatic object storage, caching, change tracking, object identity, etc. LINQ to DB explicitly translates your LINQ queries into SQL and maps the result to your application object model. Instead of hiding your database from you, LINQ to DB concentrates on high performance, generating clear, readable and human friendly SQL, and close to SQL programming model including DDL and DML operations. In fact, you can consider LINQ to DB as type-safe SQL embedded in C#, VB.NET, and any other .NET languages. LINQ to DB is a straightforward LINQ into SQL translator that avoids any magic, implicity, and unexpected surprises.

Get started

The following example demonstrates how to start using LINQ to DB.

  • Create a project.
  • Add LINQ to DB NuGet into your solution.
  • Use the following code to test the library:
using System;
using System.Linq;

using LinqToDB.DataProvider.SqlServer;

namespace ConsoleApplication1
{
    public class Categories
    {
        public int    CategoryID;
        public string CategoryName;
        public string Description;
        public byte[] Picture;
    }

    class Program
    {
        const string ConnectionString =
            "Data Source=.;Database=Northwind;Integrated Security=SSPI";

        static void Main()
        {
            using (var db = SqlServerTools.CreateDataConnection(ConnectionString))
            {
                var q =
                    from c in db.GetTable<Categories>()
                    select c;

                foreach (var category in q)
                {
                    Console.WriteLine("ID : {0}, Name : {1}",
                        category.CategoryID,
                        category.CategoryName);
                }
            }
        }
    }
}

More advanced example (using app.config configuration and entity mapping attributes):

App.config
<?xml version="1.0"?>
<configuration>
    <connectionStrings>
        <add name="Northwind" 
            connectionString="Data Source=.;Database=Northwind;Integrated Security=SSPI"
            providerName="System.Data.SqlClient" />
    </connectionStrings>
</configuration>
Program.cs
using System;
using System.Linq;

using LinqToDB.Data;
using LinqToDB.Mapping;

namespace ConsoleApplication1
{
    [Table("Categories")]
    public class Category
    {
        [PrimaryKey, Identity] public int    CategoryID;
        [Column, NotNull]      public string CategoryName;
        [Column,    Nullable]  public string Description;
        [Column,    Nullable]  public byte[] Picture;
    }

    class Program
    {
        static void Main()
        {
            using (var db = new DataConnection())
            {
                var q =
                    from c in db.GetTable<Category>()
                    select c;

                foreach (var category in q)
                {
                    Console.WriteLine("ID : {0}, Name : {1}",
                        category.CategoryID,
                        category.CategoryName);
                }
            }
        }
    }
}

Supported databases

  • DB2
  • Firebird
  • Informix
  • Microsoft Access
  • Microsoft Sql Server
  • Microsoft SqlCe
  • MySql
  • Oracle
  • PostgreSQL
  • SQLite
  • Sybase ASE

Supported frameworks

  • .NET 4.x
  • Silverlight 4+
  • Mono

Links

July 5, 2012

Nemerle pattern matching and algebraic data types

Pattern matching is one of the core features of functional programming. But you do not have to know functional programming to understand pattern matching and algebraic data types. You do not even need to know what a function is. You only need to know a little bit about programming.

No functions, no alien languages with the syntax from another planet. Only C# and Nemerle.