Skip to content
Back to search

linq2db

Linq to database provider.

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Checked today

Check it deeper on your machine

It has changed since its scan on 11 Nov 2026.

As a Claude Code plugin, install it and then ask Claude Code:

/plugin marketplace add keithmackay/mackayi/plugin install scanskillsafety@mackayiDo a deep scan of https://github.com/linq2db/linq2db with scanskillsafety

Or from a terminal, clone it and run it:

git clone https://github.com/keithmackay/scanskillsafety-skill ~/.claude/skills/scanskillsafetynode ~/.claude/skills/scanskillsafety/cli.cjs --deep 'https://github.com/linq2db/linq2db'

It checks the exact commit: every file, its packages against OSV (api.osv.dev), how it compares with this page's scan (findsafeskills.com receives the repository's address), and, if you agree, Claude reading every file with your own Claude subscription. It never runs the code.

Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/linq2db--linq2db/badge.svg)](/listings/linq2db--linq2db)

HTML

<a href="/listings/linq2db--linq2db"><img src="/api/listings/linq2db--linq2db/badge.svg" alt="findsafeskills safety rating" /></a>

Install

i

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

README.md · README · 763 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

This file has changed since it was scanned, so this is not exactly the text that was scanned, and no line is marked. The findings are listed with the safety scan above.

  1. # LINQ to DB
  2. [![Discord](https://img.shields.io/discord/1089930409577545948?label=discord)](https://discord.gg/PcV6pTXt4s) [![NuGet Version](https://img.shields.io/nuget/vpre/linq2db)](https://www.nuget.org/profiles/LinqToDB) [![License](https://img.shields.io/github/license/linq2db/linq2db)](https://github.com/linq2db/linq2db/blob/master/MIT-LICENSE.txt)
  3. [!["good first issue" tasks](https://img.shields.io/github/issues/linq2db/linq2db/good%20first%20issue.svg)](https://github.com/linq2db/linq2db/issues?q=is%3Aopen+is%3Aissue+label%3A%22good+first+issue%22)
  4. [![Master branch build](https://img.shields.io/azure-devops/build/linq2db/linq2db/5/master?label=build%20(master))](https://dev.azure.com/linq2db/linq2db/_build?definitionId=5&_a=summary) [![Latest build](https://img.shields.io/azure-devops/build/linq2db/linq2db/5?label=build%20(latest))](https://dev.azure.com/linq2db/linq2db/_build?definitionId=5&_a=summary)
  5. LINQ to DB is the fastest LINQ database access library offering a simple, light, fast, and type-safe layer between your POCOs and your database.
  6. 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.
  7. 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.
  8. In other words **LINQ to DB is type-safe SQL**.
  9. **LINQ to DB** also very nice for F# developers (see Tests/FSharp and Source/LinqToDB.FSharp project for details).
  10. Development version nugets [feeds](https://dev.azure.com/linq2db/linq2db/_artifacts/feed/linq2db) ([how to use](https://docs.microsoft.com/en-us/nuget/consume-packages/install-use-packages-visual-studio#package-sources))
  11. ## Standout Features
  12. - Rich Querying API:
  13. - [Explicit Join Syntax](https://linq2db.github.io/articles/sql/join-operators.html) (In addition to standard LINQ join syntax)
  14. - [CTE Support](https://linq2db.github.io/articles/sql/cte.html)
  15. - [Bulk Copy/Insert](https://linq2db.github.io/articles/sql/bulk-copy.html)
  16. - [Window/Analytic Functions](https://linq2db.github.io/articles/sql/window-functions-%28analytic-functions%29.html)
  17. - [Merge API](https://linq2db.github.io/articles/sql/merge/merge-api-description.html)
  18. - Extensibility:
  19. - [Ability to Map Custom SQL to Static Functions](https://github.com/linq2db/linq2db/tree/master/Source/LinqToDB/Sql/)
  20. See [Github.io documentation](https://linq2db.github.io/index.html) for more details.
  21. <!-- You can visit our [blog](http://blog.linq2db.com/) -->
  22. Code examples and demos can be found [here](https://github.com/linq2db/examples) or in [tests](https://github.com/linq2db/linq2db/tree/master/Tests/Linq).
  23. [Release notes](https://github.com/linq2db/linq2db/wiki/Releases-and-Roadmap) page.
  24. ### Related Linq To DB and 3rd-party projects
  25. - [linq2db.EntityFrameworkCore](https://github.com/linq2db/linq2db/tree/master/Source/LinqToDB.EntityFrameworkCore) (adds support for linq2db functionality in EF.Core projects)
  26. - [linq2db.Identity](https://github.com/linq2db/linq2db/tree/master/Source/LinqToDB.Identity) - ASP.NET Core Identity provider using Linq To DB
  27. - [LINQPad Driver](https://github.com/linq2db/linq2db/tree/master/Source/LinqToDB.LINQPad)
  28. - [DB2 iSeries Provider](https://github.com/LinqToDB4iSeries/Linq2DB4iSeries)
  29. - [ASP.NET Core Template](https://github.com/David-Mawer/LINQ2DB-MVC-Core-5)
  30. - [PostGIS extensions for linq2db](https://github.com/apdevelop/linq2db-postgis-extensions)
  31. Notable open-source users:
  32. - [nopCommerce](https://github.com/nopSolutions/nopCommerce) - popular open-source e-commerce solution
  33. - [OdataToEntity](https://github.com/voronov-maxim/OdataToEntity) - library to create OData service from database context
  34. - [SunEngine](https://github.com/sunengine/SunEngine) - site, blog and forum engine
  35. Unmantained projects:
  36. - [IdentityServer4.LinqToDB](https://github.com/linq2db/IdentityServer4.LinqToDB) - IdentityServer4 persistence layer using Linq To DB
  37. ## Configuring connection strings
  38. ### Passing Into Constructor
  39. You can simply pass connection string into `DataConnection` or `DataContext` constructor using [`DataOptions`](https://linq2db.github.io/api/linq2db/linq2db--LinqToDB.DataOptions.html) class.
  40. Minimal configuration example:
  41. ```cs
  42. var db = new DataConnection(
  43. new DataOptions()
  44. .UseSqlServer(@"Server=.\;Database=Northwind;Trusted_Connection=True;"));
  45. ```
  46. Use connection configuration action to setup SqlClient-specific authentication token:
  47. ```cs
  48. var options = new DataOptions()
  49. .UseSqlServer(connectionString, SqlServerVersion.v2017, SqlServerProvider.MicrosoftDataSqlClient)
  50. .UseBeforeConnectionOpened(cn =>
  51. {
  52. ((SqlConnection)cn).AccessToken = accessToken;
  53. });
  54. // pass configured options to data context constructor
  55. var dc = new DataContext(options);
  56. ```
  57. > [!TIP]
  58. > There are a lot of configuration methods on `DataOptions` you can use.
  59. > [!TIP]
  60. > It is recommended to create configured `DataOptions` instance once and use it everywhere. E.g. you can register it in your DI container.
  61. ### Using Config File (.NET Framework)
  62. In your `web.config` or `app.config` make sure you have a connection string (check [this file](https://github.com/linq2db/linq2db/blob/master/Source/LinqToDB/ProviderName.cs) for supported providers):
  63. ```xml
  64. <connectionStrings>
  65. <add name="Northwind"
  66. connectionString = "Server=.\;Database=Northwind;Trusted_Connection=True;"
  67. providerName = "SqlServer" />
  68. </connectionStrings>
  69. ```
  70. ### Using Connection String Settings Provider
  71. Alternatively, you can implement custom settings provider with `ILinqToDBSettings` interface, for example:
  72. ```cs
  73. public class ConnectionStringSettings : IConnectionStringSettings
  74. {
  75. public string ConnectionString { get; set; }
  76. public string Name { get; set; }
  77. public string ProviderName { get; set; }
  78. public bool IsGlobal => false;
  79. }
  80. public class MySettings : ILinqToDBSettings
  81. {
  82. public IEnumerable<IDataProviderSettings> DataProviders
  83. => Enumerable.Empty<IDataProviderSettings>();
  84. public string DefaultConfiguration => "SqlServer";
  85. public string DefaultDataProvider => "SqlServer";
  86. public IEnumerable<IConnectionStringSettings> ConnectionStrings
  87. {
  88. get
  89. {
  90. // note that you can return multiple ConnectionStringSettings instances here
  91. yield return
  92. new ConnectionStringSettings
  93. {
  94. Name = "Northwind",
  95. ProviderName = ProviderName.SqlServer,
  96. ConnectionString =
  97. @"Server=.\;Database=Northwind;Trusted_Connection=True;"
  98. };
  99. }
  100. }
  101. }
  102. ```
  103. And later just set on program startup before the first query is done (Startup.cs for example):
  104. ```cs
  105. DataConnection.DefaultSettings = new MySettings();
  106. ```
  107. ### Use with ASP.NET Core and Dependency Injection
  108. See [article](https://linq2db.github.io/articles/get-started/asp-dotnet-core/index.html).
  109. ## Define **POCO** class
  110. You can generate POCO classes from your database using [linq2db.cli](https://www.nuget.org/packages/linq2db.cli) `dotnet tool`.
  111. 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.
  112. ### Configuration using mapping attributes
  113. ```c#
  114. using System;
  115. using LinqToDB.Mapping;
  116. [Table("Products")]
  117. public class Product
  118. {
  119. [PrimaryKey, Identity]
  120. public int ProductID { get; set; }
  121. [Column("ProductName"), NotNull]
  122. public string Name { get; set; }
  123. [Column]
  124. public int VendorID { get; set; }
  125. [Association(ThisKey = nameof(VendorID), OtherKey=nameof(Vendor.ID))]
  126. public Vendor Vendor { get; set; }
  127. // ... other columns ...
  128. }
  129. ```
  130. 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:
  131. ```c#
  132. using System;
  133. using LinqToDB.Mapping;
  134. [Table("Products")]
  135. public class Product
  136. {
  137. [PrimaryKey, Identity]
  138. public int ProductID { get; set; }
  139. // Property `Name` will be ignored as it lacks `Column` attibute.
  140. public string Name { get; set; }
  141. }
  142. ```
  143. ### Fluent Configuration
  144. 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`.
  145. With Fluent approach you can configure only things that require it explicitly. All other properties will be inferred by linq2db:
  146. ```c#
  147. // IMPORTANT: configure mapping schema instance only once
  148. // and use it with all your connections that need those mappings
  149. // Never create new mapping schema for each connection as
  150. // it will seriously harm performance
  151. var myFluentMappings = new MappingSchema();
  152. var builder = new FluentMappingBuilder(mappingSchema);
  153. builder.Entity<Product>()
  154. .HasTableName("Products")
  155. .HasSchemaName("dbo")
  156. .HasIdentity(x => x.ProductID)
  157. .HasPrimaryKey(x => x.ProductID)
  158. .Ignore(x => x.SomeNonDbProperty)
  159. .Property(x => x.TimeStamp)
  160. .HasSkipOnInsert()
  161. .HasSkipOnUpdate()
  162. .Association(x => x.Vendor, x => x.VendorID, x => x.VendorID, canBeNull: false)
  163. ;
  164. //... other mapping configurations
  165. // commit configured mappings to mapping schema
  166. builder.Build();
  167. ```
  168. 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.
  169. To use your `MappingSchema` instance you should pass it `DataConnection` or `DataContext` constructor:
  170. ```cs
  171. var options = new DataOptions()
  172. .UseSqlServer(@"Server=.\;Database=Northwind;Trusted_Connection=True;")
  173. .UseMappingSchema(myFluentMappings);
  174. var db = new DataConnection(option);
  175. ```
  176. ### Inferred Configuration
  177. 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:
  178. - Linq To DB will not infer primary key even if class has property called `ID`;
  179. - it will not infer nullability of reference types if you don't use nullable reference types annotations;
  180. - associations will not be automatically configured.
  181. ```c#
  182. using System;
  183. public class Product
  184. {
  185. public int ProductID { get; set; }
  186. public string Name { get; set; }
  187. public int VendorID { get; set; }
  188. public Vendor Vendor { get; set; }
  189. // ... other columns ...
  190. }
  191. ```
  192. 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`.
  193. This approach is not generally recommended.
  194. ### DataConnection class
  195. 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:
  196. ```c#
  197. public class DbNorthwind : LinqToDB.Data.DataConnection
  198. {
  199. public DbNorthwind() : base("Northwind") { }
  200. public ITable<Product> Product => this.GetTable<Product>();
  201. public ITable<Category> Category => this.GetTable<Category>();
  202. // ... other tables ...
  203. }
  204. ```
  205. 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.
  206. And now let's get some data:
  207. ```cs
  208. using LinqToDB;
  209. public static List<Product> GetProducts()
  210. {
  211. using var db = new DbNorthwind();
  212. var query = from p in db.Product
  213. where p.ProductID > 25
  214. orderby p.Name descending
  215. select p;
  216. return query.ToList();
  217. }
  218. ```
  219. 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](https://linq2db.github.io/articles/general/managing-data-connection.html)).
  220. ## Queries
  221. ### Selecting Columns
  222. Most times we get the entire row from the database:
  223. ```c#
  224. from p in db.Product
  225. where p.ProductID == 5
  226. select p;
  227. ```
  228. 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.
  229. ```c#
  230. from p in db.Product
  231. orderby p.Name descending
  232. select new Product
  233. {
  234. Name = p.Name
  235. };
  236. ```
  237. ### Composing queries
  238. 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.
  239. ```c#
  240. public static Product[] GetProducts(bool onlyActive, string searchFor)
  241. {
  242. using var db = new DbNorthwind();
  243. var products = from p in db.Product
  244. select p;
  245. if (onlyActive)
  246. {
  247. products = from p in products
  248. where !p.Discontinued
  249. select p;
  250. }
  251. if (searchFor != null)
  252. {
  253. products = from p in products
  254. where p.Name.Contains(searchFor)
  255. select p;
  256. }
  257. return products.ToArray();
  258. }
  259. ```
  260. ### Paging
  261. 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.
  262. 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.
  263. ```c#
  264. public static List<Product> Search(
  265. string searchFor,
  266. int currentPage,
  267. int pageSize,
  268. out int totalRecords)
  269. {
  270. using var db = new DbNorthwind();
  271. var products = from p in db.Product
  272. select p;
  273. if (searchFor != null)
  274. {
  275. products = from p in products
  276. where p.Name.Contains(searchFor)
  277. select p;
  278. }
  279. totalRecords = products.Count();
  280. return products.Skip((currentPage - 1) * pageSize).Take(pageSize).ToList();
  281. }
  282. ```
  283. ### Joins
  284. 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:
  285. ```c#
  286. from p in db.Product
  287. join c in db.Category on p.CategoryID equals c.CategoryID
  288. select new Product
  289. {
  290. Name = p.Name,
  291. Category = c
  292. };
  293. ```
  294. and a **LEFT JOIN** query like this:
  295. ```c#
  296. from p in db.Product
  297. from c in db.Category.Where(q => q.CategoryID == p.CategoryID).DefaultIfEmpty()
  298. select new Product
  299. {
  300. Name = p.Name,
  301. Category = c
  302. };
  303. ```
  304. [More samples are here](https://linq2db.github.io/articles/sql/join-operators.html)
  305. ### Creating your POCOs
  306. 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:
  307. ```c#
  308. from p in db.Product
  309. from c in db.Category.Where(q => q.CategoryID == p.CategoryID).DefaultIfEmpty()
  310. select new Product(c);
  311. ```
  312. 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:
  313. ```c#
  314. from p in db.Product
  315. from c in db.Category.Where(q => q.CategoryID == p.CategoryID).DefaultIfEmpty()
  316. select Product.Build(p, c);
  317. ```
  318. For this to work, we need a function in the `Product` class that looks like this:
  319. ```c#
  320. public static Product Build(Product? product, Category category)
  321. {
  322. if (product != null)
  323. {
  324. product.Category = category;
  325. }
  326. return product;
  327. }
  328. ```
  329. 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.
  330. ### Insert
  331. 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.
  332. ```c#
  333. using LinqToDB;
  334. using var db = new DbNorthwind();
  335. db.Insert(product);
  336. ```
  337. 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:
  338. ```c#
  339. using LinqToDB;
  340. using var db = new DbNorthwind();
  341. product.ProductID = db.InsertWithInt32Identity(product);
  342. ```
  343. There is also `InsertOrReplace` that updates a database record if it was found by primary key or adds it otherwise.
  344. If you need to insert only certain fields, or use values generated by the database, you could write:
  345. ```c#
  346. using LinqToDB;
  347. using var db = new DbNorthwind();
  348. db.Product
  349. .Value(p => p.Name, product.Name)
  350. .Value(p => p.UnitPrice, 10.2m)
  351. .Value(p => p.Added, () => Sql.CurrentTimestamp)
  352. .Insert();
  353. ```
  354. Use of this method also allows us to build insert statements like this:
  355. ```c#
  356. using LinqToDB;
  357. using var db = new DbNorthwind();
  358. var statement = db.Product
  359. .Value(p => p.Name, product.Name)
  360. .Value(p => p.UnitPrice, 10.2m);
  361. if (storeAdded) statement.Value(p => p.Added, () => Sql.CurrentTimestamp);
  362. statement.Insert();
  363. ```
  364. ### Update
  365. Updating records follows similar pattern to `Insert`. We have an extension method that updates all the columns in the database:
  366. ```c#
  367. using LinqToDB;
  368. using var db = new DbNorthwind();
  369. db.Update(product);
  370. ```
  371. And we also have a lower level update mechanism:
  372. ```c#
  373. using LinqToDB;
  374. using var db = new DbNorthwind();
  375. db.Product
  376. .Where(p => p.ProductID == product.ProductID)
  377. .Set(p => p.Name, product.Name)
  378. .Set(p => p.UnitPrice, product.UnitPrice)
  379. .Update();
  380. ```
  381. Similarly, we can break an update query into multiple pieces if needed:
  382. ```c#
  383. using LinqToDB;
  384. using var db = new DbNorthwind();
  385. var statement = db.Product
  386. .Where(p => p.ProductID == product.ProductID)
  387. .Set(p => p.Name, product.Name);
  388. if (updatePrice) statement = statement.Set(p => p.UnitPrice, product.UnitPrice);
  389. statement.Update();
  390. ```
  391. You're not limited to a single record update. For example, we could discontinue all the products that are no longer in stock:
  392. ```c#
  393. using LinqToDB;
  394. using var db = new DbNorthwind();
  395. db.Product
  396. .Where(p => p.UnitsInStock == 0)
  397. .Set(p => p.Discontinued, true)
  398. .Update();
  399. ```
  400. ### Delete
  401. Similar to how you update records, you can also delete records:
  402. ```c#
  403. using LinqToDB;
  404. using var db = new DbNorthwind();
  405. db.Product
  406. .Where(p => p.Discontinued)
  407. .Delete();
  408. ```
  409. ### Bulk Copy
  410. Bulk copy feature supports the transfer of large amounts of data into a table from another data source. For more details read this [article](https://linq2db.github.io/articles/sql/bulk-copy.html).
  411. ```c#
  412. using LinqToDB.Data;
  413. [Table("ProductsTemp")]
  414. public class ProductTemp
  415. {
  416. [PrimaryKey]
  417. public int ProductID { get; set; }
  418. [Column("ProductName"), NotNull]
  419. public string Name { get; set; }
  420. // ... other columns ...
  421. }
  422. var list = new List<ProductTemp>();
  423. // ... populate list ...
  424. using var db = new DbNorthwind();
  425. db.BulkCopy(list);
  426. ```
  427. ### Transactions
  428. 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.
  429. ```c#
  430. using var db = new DbNorthwind();
  431. db.BeginTransaction();
  432. // or
  433. //using var tr = db.BeginTransaction();
  434. // ... select / insert / update / delete ...
  435. if (somethingIsNotRight)
  436. {
  437. db.RollbackTransaction();
  438. // or
  439. // tr.Rollback();
  440. }
  441. else
  442. {
  443. db.CommitTransaction();
  444. // or
  445. // tr.Commit();
  446. }
  447. ```
  448. Also, you can use .NET built-in `TransactionScope` class:
  449. ```c#
  450. using var transaction = new TransactionScope();
  451. // or for async code
  452. // using var transaction = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled);
  453. using var db = new DbNorthwind();
  454. ...
  455. transaction.Complete();
  456. ```
  457. 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.
  458. This difference in behavior matters when used with `TransactionScope`:
  459. ```c#
  460. using var db = new LinqToDB.Data.DataConnection("provider name", "connection string");
  461. var product = db.GetTable<Product>()
  462. .FirstOrDefault(); // connection opened here
  463. var scope = new TransactionScope();
  464. // this transaction was not attached to connection
  465. // because it was opened earlier
  466. product.Name = "Lollipop";
  467. db.Update(product);
  468. scope.Dispose();
  469. // no transaction rollback happed, "Lollipop" has been saved
  470. ```
  471. A `DataConnection` is attached with ambient transaction in moment it is opened. Any `TransactionScope`s 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.
  472. 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`:
  473. ```c#
  474. public class DbNorthwind : LinqToDB.Data.DataConnection
  475. {
  476. public DbNorthwind() : base("Northwind")
  477. {
  478. (this as IDataContext).CloseAfterUse = true;
  479. }
  480. }
  481. ```
  482. ### Merge
  483. [Here](https://linq2db.github.io/articles/sql/merge/merge-api.html) you can read about SQL MERGE support.
  484. ### Window (Analytic) Functions
  485. [Here](https://linq2db.github.io/articles/sql/window-functions-%28analytic-functions%29.html) you can read about Window (Analytic) Functions support.
  486. ## MiniProfiler
  487. If you would like to use [MiniProfiler](https://github.com/MiniProfiler/dotnet) or other profiling tool that wraps ADO.NET provider classes, you need to configure our regular `DataConnection` to use wrapped connection.
  488. ```c#
  489. // example of SQL Server-backed data connection with MiniProfiler enabled for debug builds
  490. public class DbDataContext : DataConnection
  491. {
  492. // let's use profiler only for debug builds
  493. #if !DEBUG
  494. // regular non-profiled constructor
  495. public DbDataContext() : base("Northwind") {}
  496. #else
  497. public DbDataContext()
  498. : base(
  499. new DataOptions()
  500. .UseSqlServer(connectionString, SqlServerVersion.v2012)
  501. .UseConnectionFactory(GetConnection)
  502. .UseInterceptor(new UnwrapProfilerInterceptor()))
  503. {
  504. }
  505. // wrap connection into profiler wrapper
  506. private static DbConnection GetConnection(DataOptions options)
  507. {
  508. // create provider-specific connection instance. SqlConnection in our case
  509. var dbConnection = new SqlConnection(options.ConnectionOptions.ConnectionString);
  510. // wrap it by profiler's connection implementation
  511. return new StackExchange.Profiling.Data.ProfiledDbConnection(
  512. dbConnection,
  513. MiniProfiler.Current);
  514. }
  515. // define UnwrapDataObjectInterceptor
  516. sealed class UnwrapProfilerInterceptor : UnwrapDataObjectInterceptor
  517. {
  518. public override DbConnection UnwrapConnection(IDataContext dataContext, DbConnection connection)
  519. {
  520. return connection is ProfiledDbConnection c ? c.WrappedConnection : connection;
  521. }
  522. public override DbTransaction UnwrapTransaction(IDataContext dataContext, DbTransaction transaction)
  523. {
  524. return transaction is ProfiledDbTransaction t ? t.WrappedTransaction : transaction;
  525. }
  526. public override DbCommand UnwrapCommand(IDataContext dataContext, DbCommand command)
  527. {
  528. return command is ProfiledDbCommand c ? c.WrappedCommand : command;
  529. }
  530. public override DbDataReader UnwrapDataReader(IDataContext dataContext, DbDataReader dataReader)
  531. {
  532. return dataReader is ProfiledDbDataReader dr ? dr.WrappedReader : dataReader;
  533. }
  534. }
  535. #endif
  536. }
  537. ```
  538. ## F#
  539. ### Sample query with load child relations
  540. ```fsharp
  541. let getPerson (db: IDataContext) (id: int) =
  542. let persons = db.GetTable<Person>().LoadWith(fun x -> x.Patient)
  543. let person =
  544. query {
  545. for p in persons do
  546. where (p.ID = id)
  547. exactlyOne
  548. }
  549. person
  550. ```
  551. ## More
  552. Still have questions left? Check out our [documentation site](https://linq2db.github.io) and [FAQ](https://linq2db.github.io/articles/faq.html)
  553. ### Supported by
  554. [![JetBrains logo.](https://resources.jetbrains.com/storage/products/company/brand/logos/jetbrains.svg)](https://jb.gg/OpenSource)

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.