Getting started
Expoloer LinqSharp
Exploring LinqSharp requires a clear understanding of the SQL statements it generates.
Expression trees
Expression trees established C# as a truly formidable language.
We can easily convert Lambda into Expression Tree via the LINQ API, while .NET allows us to convert Expression Tree into any form we want.
Most languages do not provide compile-time conversion of Lambdas to Expression Trees, which is one of the reasons why the .NET ORM can be designed to be very easy to use.
It is worth pointing out that true generics support is also indispensable, which makes the expression tree more scalable.
Print SQL
If you don't have a test database available, try Northwnd.
With this simple sales network database, we'll show you how to use LinqSharp.
-
Create a Console Application ( .NET 7 ).
-
Use the follow command to install Northwnd:
dotnet add package Microsoft.EntityFrameworkCore --version 7.0.0 dotnet add package Microsoft.EntityFrameworkCore.Design --version 7.0.0 dotnet add package Microsoft.EntityFrameworkCore.Sqlite --version 7.0.0 dotnet add package LinqSharp --version 7.0 dotnet add package Northwnd --version 7.0 dotnet add package Ink --version 0.12.1
-
Then, you need to add a
NorthwndFactory.cs
file in the root of your project:NorthwndFactory.cspublic class NorthwndFactory : IDesignTimeDbContextFactory<NorthwndContext> { private static readonly string _connectionString = "Data Source=northwnd.db"; public NorthwndContext CreateDbContext(params string[] args) { var assemblyName = Assembly.GetExecutingAssembly().GetName().Name; var options = new DbContextOptionsBuilder() .UseSqlite(_connectionString, x => x.MigrationsAssembly(assemblyName)) .Options; return new NorthwndContext(options); } }
-
Open a terminal, execute the follow script to generate a migration, and update it to database:
dotnet ef migrations add InitNorthwnd
-
Edit the
Program.cs
file:Program.csstatic void Main(string[] args) { var factory = new NorthwndFactory(); using var context = factory.CreateDbContext(); if (!context.Database.GetAppliedMigrations().Any()) { context.Database.Migrate(); context.InitializeNorthwnd(new NorthwndMemoryContext()); } var query = ( from c in context.Categories select new { c.CategoryID, c.CategoryName, } ); var sql = query.ToQueryString(); Echo.Line(sql) .Table(query); }
-
Compile and run the application, if all already done, you will get the output:
SELECT "c"."CategoryID", "c"."CategoryName" FROM "Categories" AS "c"
+------------+----------------+ | CategoryID | CategoryName | +------------+----------------+ | 1 | Beverages | | 2 | Condiments | | 3 | Confections | | 4 | Dairy Products | | 5 | Grains/Cereals | | 6 | Meat/Poultry | | 7 | Produce | | 8 | Seafood | +------------+----------------+