linq2db 6.0.0-preview.1

Prefix Reserved
This is a prerelease version of linq2db.
dotnet add package linq2db --version 6.0.0-preview.1                
NuGet\Install-Package linq2db -Version 6.0.0-preview.1                
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="linq2db" Version="6.0.0-preview.1" />                
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add linq2db --version 6.0.0-preview.1                
#r "nuget: linq2db, 6.0.0-preview.1"                
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
// Install linq2db as a Cake Addin
#addin nuget:?package=linq2db&version=6.0.0-preview.1&prerelease

// Install linq2db as a Cake Tool
#tool nuget:?package=linq2db&version=6.0.0-preview.1&prerelease                



LINQ to DB is the fastest LINQ database access library offering a simple, light, fast, and type-safe layer between your POCO objects and your database.

Architecturally it is one step above micro-ORMs like Dapper, Massive, or PetaPoco, in that you work with LINQ expressions, not with magic strings, while maintaining a thin abstraction layer between your code and the database. Your queries are checked by the C# compiler and allow for easy refactoring.

However, it's not as heavy as LINQ to SQL or Entity Framework. There is no change-tracking, so you have to manage that yourself, but on the positive side you get more control and faster access to your data.

In other words LINQ to DB is type-safe SQL.

Standout Features

See documentation for more details.

Code examples and demos can be found here or in tests.

Notable open-source users:

  • nopCommerce - popular open-source e-commerce solution
  • OdataToEntity - library to create OData service from database context
  • SunEngine - site, blog and forum engine

Configuring connection strings

Passing Into Constructor

You can simply pass connection string into DataConnection or DataContext constructor using DataOptions class.

Minimal configuration example:

var db = new DataConnection(
  new DataOptions()

Use connection configuration action to setup SqlClient-specific authentication token:

var options = new DataOptions()
  .UseSqlServer(connectionString, SqlServerVersion.v2017, SqlServerProvider.MicrosoftDataSqlClient)
  .UseBeforeConnectionOpened(cn =>
        ((SqlConnection)cn).AccessToken = accessToken;

// pass configured options to data context constructor
var dc = new DataContext(options);

[!TIP] There are a lot of configuration methods on DataOptions you can use.

[!TIP] It is recommended to create configured DataOptions instance once and use it everywhere. E.g. you can register it in your DI container.

Using Config File (.NET Framework)

In your web.config or app.config make sure you have a connection string (check this file for supported providers):

  <add name="Northwind" 
    connectionString = "Server=.\;Database=Northwind;Trusted_Connection=True;" 
    providerName     = "SqlServer" />

Using Connection String Settings Provider

Alternatively, you can implement custom settings provider with ILinqToDBSettings interface, for example:

public class ConnectionStringSettings : IConnectionStringSettings
    public string ConnectionString { get; set; }
    public string Name             { get; set; }
    public string ProviderName     { get; set; }
    public bool   IsGlobal         => false;

public class MySettings : ILinqToDBSettings
    public IEnumerable<IDataProviderSettings> DataProviders
        => Enumerable.Empty<IDataProviderSettings>();

    public string DefaultConfiguration => "SqlServer";
    public string DefaultDataProvider  => "SqlServer";

    public IEnumerable<IConnectionStringSettings> ConnectionStrings
            // note that you can return multiple ConnectionStringSettings instances here
            yield return
                new ConnectionStringSettings
                    Name             = "Northwind",
                    ProviderName     = ProviderName.SqlServer,
                    ConnectionString =

And later just set on program startup before the first query is done (Startup.cs for example):

DataConnection.DefaultSettings = new MySettings();

Use with ASP.NET Core and Dependency Injection

See article.

Define POCO class

You can generate POCO classes from your database using linq2db.cli dotnet tool.

Alternatively, you can write them manually and map to database using mapping attributes or fluent mapping configuration. Also you can use POCO classes as-is without additional mappings if they use same naming for classes and properties as table and column names in database.

Configuration using mapping attributes

using System;
using LinqToDB.Mapping;

public class Product
  [PrimaryKey, Identity]
  public int ProductID { get; set; }

  [Column("ProductName"), NotNull]
  public string Name { get; set; }

  public int VendorID { get; set; }

  [Association(ThisKey = nameof(VendorID), OtherKey = nameof(Vendor.ID))]
  public Vendor Vendor { get; set; }

  // ... other columns ...

This approach involves attributes on all properties that should be mapped. This way lets you to configure all possible things linq2db ever supports. There is one thing to mention: if you add at least one attribute into POCO, all other properties should also have attributes, otherwise they will be ignored:

using System;
using LinqToDB.Mapping;

public class Product
  [PrimaryKey, Identity]
  public int ProductID { get; set; }

  // Property `Name` will be ignored as it lacks `Column` attibute.
  public string Name { get; set; }

Fluent Configuration

This method lets you configure your mapping dynamically at runtime. Furthermore, it lets you to have several different configurations if you need so. You will get all configuration abilities available with attribute configuration. These two approaches are interchangeable in their abilities. This kind of configuration is done through the class MappingSchema.

With fluent approach you can configure only things that require it explicitly. All other properties will be inferred by Linq To DB:

// IMPORTANT: configure mapping schema instance only once
// and use it with all your connections that need those mappings
// Never create new mapping schema for each connection as
// it will seriously harm performance
var myFluentMappings = new MappingSchema();
var builder          = mappingSchema.GetFluentMappingBuilder();

    .HasIdentity(x => x.ProductID)
    .HasPrimaryKey(x => x.ProductID)
    .Ignore(x => x.SomeNonDbProperty)
    .Property(x => x.TimeStamp)
    .Association(x => x.Vendor, x => x.VendorID, x => x.VendorID, canBeNull: false)

//... other mapping configurations

// commit configured mappings to mapping schema

In this example we configured only three properties and one association. We let Linq To DB to infer all other properties as columns with same name as property.

To use your MappingSchema instance you should pass it DataConnection or DataContext constructor:

var options = new DataOptions()

var db = new DataConnection(option);

Inferred Configuration

This approach involves no attributes at all. In this case Linq To DB will use POCO's name as table name and property names as column names (with exact same casing, which could be important for case-sensitive databases). This might seem to be convenient, but there are some restrictions:

  • Linq To DB will not infer primary key even if class has property called ID;
  • it will not infer nullability of reference types if you don't use nullable reference types annotations;
  • associations will not be automatically configured.
using System;
using LinqToDB.Mapping;

public class Product
  public int    ProductID { get; set; }

  public string Name      { get; set; }

  public int    VendorID  { get; set; }

  public Vendor Vendor    { get; set; }

  // ... other columns ...

This way Linq To DB will auto-configure Product class to map to Product table with fields ProductID, Name, and VendorID. POCO will not get ProductID property treated as primary key. And there will be no association with Vendor.

This approach is not generally recommended.

DataConnection class

At this point LINQ to DB doesn't know how to connect to our database or which POCOs go with what database. All this mapping is done through a DataConnection class:

public class DbNorthwind : LinqToDB.Data.DataConnection
  public DbNorthwind() : base("Northwind") { }

  public ITable<Product>  Product  => this.GetTable<Product>();
  public ITable<Category> Category => this.GetTable<Category>();

  // ... other tables ...

We call the base constructor with the "Northwind" parameter. This parameter (called configuration name) has to match the name="Northwind" we defined above as name of our connection string. We also added convenience properties for Product and Category mapping classes to write LINQ queries.

And now let's get some data:

using LinqToDB;
using LinqToDB.Common;

public static List<Product> GetProducts()
  using var db = new DbNorthwind();

  var query = from p in db.Product
                where p.ProductID > 25
                orderby p.Name descending
                select p;

  return query.ToList();

Make sure you always wrap your DataConnection class (in our case DbNorthwind) in a using statement. This is required for proper resource management, like releasing the database connections back into the pool (more details).


Selecting Columns

Most times we get the entire row from the database:

from p in db.Product
where p.ProductID == 5
select p;

However, sometimes getting all the fields is too wasteful so we want only certain fields, but still use our POCOs; something that is challenging for libraries that rely on object tracking, like LINQ to SQL.

from p in db.Product
orderby p.Name descending
select new Product
  Name = p.Name

Composing queries

Rather than concatenating strings we can 'compose' LINQ expressions. In the example below the final SQL will be different if onlyActive is true or false, or if searchFor is not null.

public static Product[] GetProducts(bool onlyActive, string searchFor)
  using var db = new DbNorthwind();
  var products = from p in db.Product 
                   select p;

  if (onlyActive)
    products = from p in products 
               where !p.Discontinued 
               select p;

  if (searchFor != null)
    products = from p in products 
                 where p.Name.Contains(searchFor) 
                 select p;

  return products.ToArray();


A lot of times we need to write code that returns only a subset of the entire dataset. We expand on the previous example to show what a product search function could look like.

Keep in mind that the code below will query the database twice. Once to find out the total number of records, something that is required by many paging controls, and once to return the actual data.

public static List<Product> Search(
                  string  searchFor,
                  int     currentPage,
                  int     pageSize,
                  out int totalRecords)
  using var db = new DbNorthwind();
  var products = from p in db.Product 
                   select p;

  if (searchFor != null)
    products = from p in products 
               where p.Name.Contains(searchFor) 
               select p;

  totalRecords = products.Count();

  return products.Skip((currentPage - 1) * pageSize).Take(pageSize).ToList();


This assumes we added a Category class, just like we did with the Product class, defined all the fields, and defined table access property in our DbNorthwind data access class. We can now write an INNER JOIN query like this:

from p in db.Product
join c in db.Category on p.CategoryID equals c.CategoryID
select new Product
  Name = p.Name,
  Category = c

and a LEFT JOIN query like this:

from p in db.Product
from c in db.Category.Where(q => q.CategoryID == p.CategoryID).DefaultIfEmpty()
select new Product
  Name = p.Name,
  Category = c

More samples are here

Creating your POCOs

In the previous example we assign an entire Category object to our product, but what if we want all the fields in our Product class, but we don't want to specify every field by hand? Unfortunately, we cannot write this:

from p in db.Product
from c in db.Category.Where(q => q.CategoryID == p.CategoryID).DefaultIfEmpty()
select new Product(c);

The query above assumes the Product class has a constructor that takes in a Category object. The query above won't work, but we can work around that with the following query:

from p in db.Product
from c in db.Category.Where(q => q.CategoryID == p.CategoryID).DefaultIfEmpty()
select Product.Build(p, c);

For this to work, we need a function in the Product class that looks like this:

public static Product Build(Product? product, Category category)
  if (product != null)
    product.Category = category;
  return product;

One caveat with this approach is that if you're using it with composed queries (see example above) the select Build part has to come only in the final select.


At some point we will need to add a new Product to the database. One way would be to call the Insert extension method found in the LinqToDB namespace; so make sure you import that.

using LinqToDB;

using var db = new DbNorthwind();

This inserts all the columns from our Product class, but without retrieving the generated identity value. To do that we can use InsertWith*Identity methods, like this:

using LinqToDB;

using var db = new DbNorthwind();
product.ProductID = db.InsertWithInt32Identity(product);

There is also InsertOrReplace that updates a database record if it was found by primary key or adds it otherwise.

If you need to insert only certain fields, or use values generated by the database, you could write:

using LinqToDB;

using var db = new DbNorthwind();
  .Value(p => p.Name, product.Name)
  .Value(p => p.UnitPrice, 10.2m)
  .Value(p => p.Added, () => Sql.CurrentTimestamp)

Use of this method also allows us to build insert statements like this:

using LinqToDB;

using var db = new DbNorthwind();
var statement = db.Product
                    .Value(p => p.Name, product.Name)
                    .Value(p => p.UnitPrice, 10.2m);

if (storeAdded) statement.Value(p => p.Added, () => Sql.CurrentTimestamp);



Updating records follows similar pattern to Insert. We have an extension method that updates all the columns in the database:

using LinqToDB;

using var db = new DbNorthwind();

And we also have a lower level update mechanism:

using LinqToDB;

using var db = new DbNorthwind();
  .Where(p => p.ProductID == product.ProductID)
  .Set(p => p.Name, product.Name)
  .Set(p => p.UnitPrice, product.UnitPrice)

Similarly, we can break an update query into multiple pieces if needed:

using LinqToDB;

using var db = new DbNorthwind();
var statement = db.Product
                    .Where(p => p.ProductID == product.ProductID)
                    .Set(p => p.Name, product.Name);

if (updatePrice) statement = statement.Set(p => p.UnitPrice, product.UnitPrice);


You're not limited to a single record update. For example, we could discontinue all the products that are no longer in stock:

using LinqToDB;

using var db = new DbNorthwind();
  .Where(p => p.UnitsInStock == 0)
  .Set(p => p.Discontinued, true)


Similar to how you update records, you can also delete records:

using LinqToDB;

using var db = new DbNorthwind();
  .Where(p => p.Discontinued)

Bulk Copy

Bulk copy feature supports the transfer of large amounts of data into a table from another data source. For more details read this article.

using LinqToDB.Data;

public class ProductTemp
  public int ProductID { get; set; }

  [Column("ProductName"), NotNull]
  public string Name { get; set; }

  // ... other columns ...

var list = new List<ProductTemp>();

// ... populate list ...

using var db = new DbNorthwind();


Using database transactions is easy. All you have to do is call BeginTransaction() on your DataConnection, run one or more queries, and then commit the changes by calling CommitTransaction(). If something happened and you need to roll back your changes you can either call RollbackTransaction() or throw an exception.

using var db = new DbNorthwind();
// or
//using var tr = db.BeginTransaction();
  // ... select / insert / update / delete ...

if (somethingIsNotRight)
  // or
  // tr.Rollback();
  // or
  // tr.Commit();

Also, you can use .NET built-in TransactionScope class:

using var transaction = new TransactionScope();
// or for async code
// using var transaction = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled);
using var db = new DbNorthwind();

It should be noted that there are two base classes for your "context" class: LinqToDB.Data.DataConnection and LinqToDB.DataContext. The key difference between them is in connection retention behaviour. DataConnection opens connection with first query and holds it open until dispose happens. DataContext behaves the way you might used to with Entity Framework: it opens connection per query and closes it right after query is done.

This difference in behavior matters when used with TransactionScope:

using var db = new LinqToDB.Data.DataConnection("provider name", "connection string");

var product = db.GetTable<Product>()
  .FirstOrDefault(); // connection opened here

var scope = new TransactionScope();
// this transaction was not attached to connection
// because it was opened earlier

product.Name = "Lollipop";


// no transaction rollback happed, "Lollipop" has been saved

A DataConnection is attached with ambient transaction in moment it is opened. Any TransactionScopes created after the connection is created will no effect on that connection. Replacing DataConnection with DataContext in code shown earlier will make transaction scope work as expected: the created record will be discarded with the transaction.

Although, DataContext appears to be the right class to choose, it is strongly recommended to use DataConnection instead. It's default behaviour might be changed with setting CloseAfterUse property to true:

public class DbNorthwind : LinqToDB.Data.DataConnection
  public DbNorthwind() : base("Northwind")
    (this as IDataContext).CloseAfterUse = true;


Here you can read about SQL MERGE support.

Window (Analytic) Functions

Here you can read about Window (Analytic) Functions support.


If you would like to use MiniProfiler or other profiling tool that wraps ADO.NET provider classes, you need to configure our regular DataConnection to use wrapped connection.

// example of SQL Server-backed data connection with MiniProfiler enabled for debug builds
public class DbDataContext : DataConnection
// let's use profiler only for debug builds
#if !DEBUG

  // regular non-profiled constructor
  public DbDataContext() : base("Northwind") {}
  public DbDataContext()
      : base(
          new DataOptions()
            .UseSqlServer(connectionString, SqlServerVersion.v2012)
            .UseInterceptor(new UnwrapProfilerInterceptor()))

  // wrap connection into profiler wrapper
  private static DbConnection GetConnection(DataOptions options)
     // create provider-specific connection instance. SqlConnection in our case
     var dbConnection = new SqlConnection(options.ConnectionOptions.ConnectionString);

     // wrap it by profiler's connection implementation
     return new StackExchange.Profiling.Data.ProfiledDbConnection(

  // define UnwrapDataObjectInterceptor
  sealed class UnwrapProfilerInterceptor : UnwrapDataObjectInterceptor
    public override DbConnection UnwrapConnection(IDataContext dataContext, DbConnection connection)
      return connection is ProfiledDbConnection c ? c.WrappedConnection : connection;

    public override DbTransaction UnwrapTransaction(IDataContext dataContext, DbTransaction transaction)
       return transaction is ProfiledDbTransaction t ? t.WrappedTransaction : transaction;

    public override DbCommand UnwrapCommand(IDataContext dataContext, DbCommand command)
      return command is ProfiledDbCommand c ? c.WrappedCommand : command;

    public override DbDataReader UnwrapDataReader(IDataContext dataContext, DbDataReader dataReader)
      return dataReader is ProfiledDbDataReader dr ? dr.WrappedReader : dataReader;


Still have questions left? Check out our documentation site and FAQ

Product Compatible and additional computed target framework versions.
.NET net5.0 was computed.  net5.0-windows was computed.  net6.0 is compatible.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 was computed.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed. 
.NET Core netcoreapp2.0 was computed.  netcoreapp2.1 was computed.  netcoreapp2.2 was computed.  netcoreapp3.0 was computed.  netcoreapp3.1 was computed. 
.NET Standard netstandard2.0 is compatible.  netstandard2.1 was computed. 
.NET Framework net461 was computed.  net462 is compatible.  net463 was computed.  net47 was computed.  net471 was computed.  net472 was computed.  net48 was computed.  net481 was computed. 
MonoAndroid monoandroid was computed. 
MonoMac monomac was computed. 
MonoTouch monotouch was computed. 
Tizen tizen40 was computed.  tizen60 was computed. 
Xamarin.iOS xamarinios was computed. 
Xamarin.Mac xamarinmac was computed. 
Xamarin.TVOS xamarintvos was computed. 
Xamarin.WatchOS xamarinwatchos was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages (112)

Showing the top 5 NuGet packages that depend on linq2db:

Package Downloads

Allows to execute Linq to DB (linq2db) queries in Entity Framework Core DbContext.


LINQ to DB ASP.NET Core Extensions adds ability to configure ASP.NET Core application for Linq To DB usage.


LINQ to SqlServer is a data access technology that provides a run-time infrastructure for managing relational data as objects. Install this package only if you want to use database model scaffolding using T4 templates (requires Visual Studio or Rider), otherwise you should use linq2db package.


LINQ to PostgreSQL is a data access technology that provides a run-time infrastructure for managing relational data as objects. Install this package only if you want to use database model scaffolding using T4 templates (requires Visual Studio or Rider), otherwise you should use linq2db package.


LINQ to MySql is a data access technology that provides a run-time infrastructure for managing relational data as objects. Install this package only if you want to use database model scaffolding using T4 templates (requires Visual Studio or Rider), otherwise you should use linq2db package.

GitHub repositories (16)

Showing the top 5 popular GitHub repositories that depend on linq2db:

Repository Stars
Bitwarden infrastructure/backend (API, database, Docker, etc).
ASP.NET Core eCommerce software. nopCommerce is a free and open-source shopping cart.
A hybrid ORM library for .NET.
A semi-opinionated library which is a source generator and a code analyser. It Source generates Value Objects
ClosedXML.Report is a tool for report generation with which you can easily export any data from your .NET classes to Excel using a XLSX-template.
Version Downloads Last updated
6.0.0-preview.1 378 6/17/2024
5.4.1 170,358 4/7/2024
5.4.0 205,532 2/20/2024
5.3.2 443,424 10/18/2023
5.3.1 95,669 10/16/2023
5.3.0 19,209 10/12/2023
5.2.2 318,328 6/8/2023
5.2.1 358,764 5/18/2023
5.2.0 77,458 5/4/2023
5.1.1 70,565 3/25/2023
5.1.0 104,060 3/16/2023
5.0.0 94,675 2/23/2023
5.0.0-rc.2 647 2/16/2023
5.0.0-rc.1 363 2/9/2023
5.0.0-preview.2 835 2/2/2023
5.0.0-preview.1 1,487 1/12/2023
4.4.1 132,026 2/2/2023
4.4.0 370,079 12/15/2022
4.3.0 667,075 10/1/2022
4.2.0 135,298 9/1/2022
4.1.1 210,916 7/7/2022
4.1.0 97,442 6/16/2022
4.0.1 156,926 5/27/2022
4.0.0 41,462 5/19/2022
3.7.0 391,204 4/7/2022
3.6.0 810,075 11/15/2021
3.5.2 179,743 11/11/2021
3.5.1 84,703 10/22/2021
3.5.0 120,332 10/14/2021
3.4.5 34,393 10/2/2021
3.4.4 102,633 9/10/2021
3.4.3 89,132 8/13/2021
3.4.2 134,194 7/9/2021
3.4.1 44,114 7/1/2021
3.4.0 156,264 6/3/2021
3.3.0 871,368 3/25/2021
3.2.3 509,941 1/4/2021
3.2.2 39,624 12/26/2020
3.2.1 24,835 12/17/2020
3.2.0 14,813 12/17/2020
3.1.6 205,477 10/31/2020
3.1.5 478,648 10/15/2020
3.1.4 33,542 10/8/2020
3.1.3 58,602 9/17/2020
3.1.2 81,201 9/3/2020
3.1.1 50,166 8/27/2020
3.1.0 38,340 8/20/2020
3.0.1 127,780 7/13/2020
3.0.0 42,524 7/10/2020
3.0.0-rc.2 516 7/5/2020
3.0.0-rc.1 12,408 6/17/2020
3.0.0-rc.0 6,894 5/30/2020
3.0.0-preview.2 57,704 3/28/2020
3.0.0-preview.1 21,829 10/17/2019
2.9.8 779,229 4/16/2020
2.9.7 125,782 3/5/2020
2.9.6 373,012 1/30/2020
2.9.5 96,924 12/30/2019
2.9.4 357,398 11/12/2019
2.9.3 71,421 10/30/2019
2.9.2 51,774 10/17/2019
2.9.1 54,842 10/3/2019
2.9.0 115,303 8/8/2019 411 3/2/2024
2.8.1 38,185 7/29/2019
2.8.0 44,830 7/25/2019
2.7.4 112,402 6/14/2019
2.7.3 13,869 6/13/2019
2.7.2 37,696 6/1/2019
2.7.1 18,362 5/23/2019
2.7.0 131,948 4/25/2019
2.6.4 202,737 2/2/2019
2.6.3 30,815 1/20/2019
2.6.2 37,273 1/3/2019
2.6.1 26,446 12/21/2018
2.6.0 22,613 12/14/2018
2.5.4 69,355 11/21/2018
2.5.3 22,113 11/20/2018
2.5.2 182,235 11/12/2018
2.5.1 22,500 11/5/2018
2.5.0 31,459 11/1/2018
2.4.0 41,354 10/4/2018
2.3.0 72,919 8/30/2018
2.2.0 73,672 7/26/2018
2.1.0 32,204 6/21/2018
2.0.0 30,038 5/17/2018
1.10.2 43,733 1/27/2018
1.10.1 9,932 11/25/2017
1.10.0 8,733 11/19/2017
1.9.0 22,865 8/30/2017
1.8.3 29,186 7/5/2017
1.8.2 9,146 6/5/2017
1.8.1 2,692 6/3/2017
1.8.0 7,301 5/12/2017
1.7.6 16,992 2/19/2017
1.7.5 9,823 12/11/2016 54,066 4/13/2016 43,041 9/7/2015 7,479 8/13/2015 43,015 2/25/2015