You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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.
You can follow our twitter bot to receive notifications about new releases. Note that currently it is only release notification bot and we don't monitor questions there.
Use connection configuration action to setup SqlClient-specific authentication token:
varoptions=newDataOptions().UseSqlServer(connectionString,SqlServerVersion.v2017,SqlServerProvider.MicrosoftDataSqlClient).UseBeforeConnectionOpened(cn =>{((SqlConnection)cn).AccessToken=accessToken;});// pass configured options to data context constructorvardc=newDataContext(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):
Alternatively, you can implement custom settings provider with ILinqToDBSettings interface, for example:
publicclassConnectionStringSettings:IConnectionStringSettings{publicstringConnectionString{get;set;}publicstringName{get;set;}publicstringProviderName{get;set;}publicboolIsGlobal=>false;}publicclassMySettings:ILinqToDBSettings{publicIEnumerable<IDataProviderSettings>DataProviders=>Enumerable.Empty<IDataProviderSettings>();publicstringDefaultConfiguration=>"SqlServer";publicstringDefaultDataProvider=>"SqlServer";publicIEnumerable<IConnectionStringSettings>ConnectionStrings{get{// note that you can return multiple ConnectionStringSettings instances hereyieldreturnnewConnectionStringSettings{Name="Northwind",ProviderName=ProviderName.SqlServer,ConnectionString=@"Server=.\;Database=Northwind;Trusted_Connection=True;"};}}}
And later just set on program startup before the first query is done (Startup.cs for example):
You can generate POCO classes from your database using linq2db.clidotnet 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
usingSystem;usingLinqToDB.Mapping;[Table("Products")]publicclassProduct{[PrimaryKey,Identity]publicintProductID{get;set;}[Column("ProductName"),NotNull]publicstringName{get;set;}[Column]publicintVendorID{get;set;}[Association(ThisKey=nameof(VendorID),OtherKey=nameof(Vendor.ID))]publicVendorVendor{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:
usingSystem;usingLinqToDB.Mapping;[Table("Products")]publicclassProduct{[PrimaryKey,Identity]publicintProductID{get;set;}// Property `Name` will be ignored as it lacks `Column` attibute.publicstringName{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 linq2db:
// 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 performancevarmyFluentMappings=newMappingSchema();varbuilder=mappingSchema.GetFluentMappingBuilder();builder.Entity<Product>().HasTableName("Products").HasSchemaName("dbo").HasIdentity(x =>x.ProductID).HasPrimaryKey(x =>x.ProductID).Ignore(x =>x.SomeNonDbProperty).Property(x =>x.TimeStamp).HasSkipOnInsert().HasSkipOnUpdate().Association(x =>x.Vendor, x =>x.VendorID, x =>x.VendorID,canBeNull:false);//... other mapping configurations// commit configured mappings to mapping schemabuilder.Build();
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:
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.
usingSystem;usingLinqToDB.Mapping;publicclassProduct{publicintProductID{get;set;}publicstringName{get;set;}publicintVendorID{get;set;}publicVendorVendor{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:
publicclassDbNorthwind:LinqToDB.Data.DataConnection{publicDbNorthwind():base("Northwind"){}publicITable<Product>Product=>this.GetTable<Product>();publicITable<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.
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).
Queries
Selecting Columns
Most times we get the entire row from the database:
frompindb.Productwherep.ProductID==5selectp;
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.
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.
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.
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:
frompindb.Product
join cindb.Category on p.CategoryID equals c.CategoryIDselectnewProduct{Name=p.Name,Category=c};
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:
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:
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.
Insert
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.
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:
Bulk copy feature supports the transfer of large amounts of data into a table from another data source. For more details read this article.
usingLinqToDB.Data;[Table("ProductsTemp")]publicclassProductTemp{[PrimaryKey]publicintProductID{get;set;}[Column("ProductName"),NotNull]publicstringName{get;set;}// ... other columns ...}varlist=newList<ProductTemp>();// ... populate list ...usingvardb=newDbNorthwind();db.BulkCopy(list);
Transactions
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.
Also, you can use .NET built-in TransactionScope class:
usingvartransaction=newTransactionScope();// or for async code// using var transaction = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled);usingvardb=newDbNorthwind();...transaction.Complete();
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:
usingvardb=newLinqToDB.Data.DataConnection("provider name","connection string");varproduct=db.GetTable<Product>().FirstOrDefault();// connection opened herevarscope=newTransactionScope();// this transaction was not attached to connection// because it was opened earlierproduct.Name="Lollipop";db.Update(product);scope.Dispose();// 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:
Here you can read about Window (Analytic) Functions support.
MiniProfiler
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 buildspublicclassDbDataContext:DataConnection{// let's use profiler only for debug builds
#if !DEBUG// regular non-profiled constructorpublicDbDataContext():base("Northwind"){}
#else
publicDbDataContext():base(newDataOptions().UseSqlServer(connectionString,SqlServerVersion.v2012).UseConnectionFactory(GetConnection).UseInterceptor(newUnwrapProfilerInterceptor())){}// wrap connection into profiler wrapperprivatestaticDbConnectionGetConnection(DataOptionsoptions){// create provider-specific connection instance. SqlConnection in our casevardbConnection=newSqlConnection(options.ConnectionOptions.ConnectionString);// wrap it by profiler's connection implementationreturnnewStackExchange.Profiling.Data.ProfiledDbConnection(dbConnection,MiniProfiler.Current);}// define UnwrapDataObjectInterceptorsealedclassUnwrapProfilerInterceptor:UnwrapDataObjectInterceptor{publicoverrideDbConnectionUnwrapConnection(IDataContextdataContext,DbConnectionconnection){returnconnectionisProfiledDbConnectionc?c.WrappedConnection:connection;}publicoverrideDbTransactionUnwrapTransaction(IDataContextdataContext,DbTransactiontransaction){returntransactionisProfiledDbTransactiont?t.WrappedTransaction:transaction;}publicoverrideDbCommandUnwrapCommand(IDataContextdataContext,DbCommandcommand){returncommandisProfiledDbCommandc?c.WrappedCommand:command;}publicoverrideDbDataReaderUnwrapDataReader(IDataContextdataContext,DbDataReaderdataReader){returndataReaderisProfiledDbDataReaderdr?dr.WrappedReader:dataReader;}}
#endif
}