From a33fbfeddf371cb16b665ba050b1f2015f0df2ce Mon Sep 17 00:00:00 2001 From: Koen Bekkenutte <2912652+kbekkenutte@users.noreply.github.com> Date: Mon, 31 May 2021 04:05:38 +0800 Subject: [PATCH] Updated readme and added new sample project --- EntityFrameworkCore.Projections.sln | 7 + README.md | 122 +++++++++++++++++- samples/ReadmeSample/ApplicationDbContext.cs | 31 +++++ samples/ReadmeSample/Entities/Order.cs | 25 ++++ samples/ReadmeSample/Entities/OrderItem.cs | 12 ++ samples/ReadmeSample/Entities/Product.cs | 11 ++ samples/ReadmeSample/Entities/User.cs | 16 +++ .../ReadmeSample/Extensions/UserExtensions.cs | 17 +++ samples/ReadmeSample/Program.cs | 49 +++++++ samples/ReadmeSample/ReadmeSample.csproj | 23 ++++ .../ProjectionExpressionGenerator.cs | 21 ++- ...s.ProjectableExtensionMethod2.verified.txt | 2 - 12 files changed, 328 insertions(+), 8 deletions(-) create mode 100644 samples/ReadmeSample/ApplicationDbContext.cs create mode 100644 samples/ReadmeSample/Entities/Order.cs create mode 100644 samples/ReadmeSample/Entities/OrderItem.cs create mode 100644 samples/ReadmeSample/Entities/Product.cs create mode 100644 samples/ReadmeSample/Entities/User.cs create mode 100644 samples/ReadmeSample/Extensions/UserExtensions.cs create mode 100644 samples/ReadmeSample/Program.cs create mode 100644 samples/ReadmeSample/ReadmeSample.csproj diff --git a/EntityFrameworkCore.Projections.sln b/EntityFrameworkCore.Projections.sln index 1e8b0c5..e76af3b 100644 --- a/EntityFrameworkCore.Projections.sln +++ b/EntityFrameworkCore.Projections.sln @@ -29,6 +29,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "EntityFrameworkCore.Project EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "EntityFrameworkCore.Projections.FunctionalTests", "tests\EntityFrameworkCore.Projections.FunctionalTests\EntityFrameworkCore.Projections.FunctionalTests.csproj", "{A36F5471-0C16-4453-811B-818326931313}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ReadmeSample", "samples\ReadmeSample\ReadmeSample.csproj", "{6F63E04C-9267-4211-8AC7-290C60331D60}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -63,6 +65,10 @@ Global {A36F5471-0C16-4453-811B-818326931313}.Debug|Any CPU.Build.0 = Debug|Any CPU {A36F5471-0C16-4453-811B-818326931313}.Release|Any CPU.ActiveCfg = Release|Any CPU {A36F5471-0C16-4453-811B-818326931313}.Release|Any CPU.Build.0 = Release|Any CPU + {6F63E04C-9267-4211-8AC7-290C60331D60}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {6F63E04C-9267-4211-8AC7-290C60331D60}.Debug|Any CPU.Build.0 = Debug|Any CPU + {6F63E04C-9267-4211-8AC7-290C60331D60}.Release|Any CPU.ActiveCfg = Release|Any CPU + {6F63E04C-9267-4211-8AC7-290C60331D60}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -75,6 +81,7 @@ Global {C8038180-36F8-4077-922B-91F428EAC7D9} = {A43F1828-D9B6-40F7-82B6-CA0070843E2F} {2F0DD7D7-867F-4478-9E22-45C114B61C46} = {F5E4436F-87F2-46AB-A9EB-59B4BF21BF7A} {A36F5471-0C16-4453-811B-818326931313} = {F5E4436F-87F2-46AB-A9EB-59B4BF21BF7A} + {6F63E04C-9267-4211-8AC7-290C60331D60} = {07584D01-2D30-404B-B0D1-32080C0CC18A} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {D17BD356-592C-4628-9D81-A04E24FF02F3} diff --git a/README.md b/README.md index 30404ce..cdfe503 100644 --- a/README.md +++ b/README.md @@ -1 +1,121 @@ -TODO \ No newline at end of file +# EntitiyFrameworkCore.Projections +Flexible projection magic for EFCore + +[![NuGet version (EntityFrameworkCore.Projections)](https://img.shields.io/nuget/v/EntityFrameworkCore.Projections.Abstractions.svg?style=flat-square)](https://www.nuget.org/packages/EntityFrameworkCore.Projections.Abstractions/) + +## NuGet packages +- EntityFrameworkCore.Projections.Abstractions [![NuGet version](https://img.shields.io/nuget/v/EntityFrameworkCore.Projections.Abstractions.svg?style=flat-square)](https://www.nuget.org/packages/EntityFrameworkCore.Projections.Abstractions/) [![NuGet](https://img.shields.io/nuget/dt/EntityFrameworkCore.Projections.Abstractions.svg?style=flat-square)](https://www.nuget.org/packages/EntityFrameworkCore.Projections.Abstractions/) +- EntityFrameworkCore.Projections [![NuGet version](https://img.shields.io/nuget/v/EntityFrameworkCore.Projections.svg?style=flat-square)](https://www.nuget.org/packages/EntityFrameworkCore.Projections/) [![NuGet](https://img.shields.io/nuget/dt/EntityFrameworkCore.Projections.svg?style=flat-square)](https://www.nuget.org/packages/EntityFrameworkCore.Projections/) + +## Getting started +TODO + +### Example +Assuming this sample: + +```csharp +class Order { + public int Id { get; set; } + public int UserId { get; set; } + public DateTime CreatedDate { get; set; } + + public decimal TaxRate { get; set; } + + public User User { get; set; } + public ICollection Items { get; set; } + + [Projectable] public decimal Subtotal => Items.Sum(item => item.Product.ListPrice * item.Quantity); + [Projectable] public decimal Tax => Subtotal * TaxRate; + [Projectable] public decimal GrandTotal => Subtotal + Tax; +} + +public static class UserExtensions { + [Projectable] + public static Order GetMostRecentOrderForUser(this User user, DateTime? cutoffDate) => + user.Orders + .Where(x => cutoffDate == null || x.CreatedDate >= cutoffDate) + .OrderByDescending(x => X.CreatedDate) + .FirstOrDefault(); +} + +var result = _dbContext.Users + .Where(x => x.UserName == "Jon") + .Select(x => new { + x.GetMostRecentOrderForUser(DateTime.UtcNow.AddDays(-30)).GrandTotal + }); + .FirstOrDefault(); +``` + +The following query gets generated (assuming SQL Server as a database provider) +```sql +SELECT ( + SELECT COALESCE(SUM([p].[ListPrice] * CAST([o].[Quantity] AS decimal(18,2))), 0.0) + FROM [OrderItem] AS [o] + INNER JOIN [Products] AS [p] ON [o].[ProductId] = [p].[Id] + WHERE ( + SELECT TOP(1) [o0].[Id] + FROM [Orders] AS [o0] + WHERE ([u].[Id] = [o0].[UserId]) AND ([o0].[CreatedDate] >= DATEADD(day, CAST(-30.0E0 AS int), GETUTCDATE())) + ORDER BY [o0].[CreatedDate] DESC) IS NOT NULL AND (( + SELECT TOP(1) [o1].[Id] + FROM [Orders] AS [o1] + WHERE ([u].[Id] = [o1].[UserId]) AND ([o1].[CreatedDate] >= DATEADD(day, CAST(-30.0E0 AS int), GETUTCDATE())) + ORDER BY [o1].[CreatedDate] DESC) = [o].[OrderId])) + (( + SELECT COALESCE(SUM([p0].[ListPrice] * CAST([o2].[Quantity] AS decimal(18,2))), 0.0) + FROM [OrderItem] AS [o2] + INNER JOIN [Products] AS [p0] ON [o2].[ProductId] = [p0].[Id] + WHERE ( + SELECT TOP(1) [o3].[Id] + FROM [Orders] AS [o3] + WHERE ([u].[Id] = [o3].[UserId]) AND ([o3].[CreatedDate] >= DATEADD(day, CAST(-30.0E0 AS int), GETUTCDATE())) + ORDER BY [o3].[CreatedDate] DESC) IS NOT NULL AND (( + SELECT TOP(1) [o4].[Id] + FROM [Orders] AS [o4] + WHERE ([u].[Id] = [o4].[UserId]) AND ([o4].[CreatedDate] >= DATEADD(day, CAST(-30.0E0 AS int), GETUTCDATE())) + ORDER BY [o4].[CreatedDate] DESC) = [o2].[OrderId])) * ( + SELECT TOP(1) [o5].[TaxRate] + FROM [Orders] AS [o5] + WHERE ([u].[Id] = [o5].[UserId]) AND ([o5].[CreatedDate] >= DATEADD(day, CAST(-30.0E0 AS int), GETUTCDATE())) + ORDER BY [o5].[CreatedDate] DESC)) AS [GrandTotal] +FROM [Users] AS [u] +WHERE [u].[UserName] = N'Jon' +``` + +Projectable properties and methods have been inlined! the generated SQL could be improved but this is what EFCore (v5) gives us. + +### How it works +Essentially there are 2 components: We have a source generator that is able to write companion Expression for properties and methods marked with the `Projectable` attribute. We then have a runtime component that intercepts any query and translates any call to a property or method marked with the `Projectable` attribute and translates the query to use the generated Expression instead. + +### FAQ + +#### Are there currently any known limitations? +There is currently no support for overloaded methods. Each method name needs to be unique within a given type. This is something that will be fixed before a proper v1 release. + +#### Is this specific to a database provider? +No; The runtime component injects itself within the EFCore query compilation pipeline and thus has no impact on the database provider used. Of course you're still limited to whatever your database provider can do. + +#### Are there performance implications that I should be aware of? +Yes and no; using EntityFrameworkCore.Projections does not add any measerable overhead on top of normal use of EFCore (Expect a proper benchmark soon...) however it does make it easier to write more complex queries. As such: Always consider the generated SQL and ensure that it's performance implications are acceptable. + +#### Can I call additional properties and methods from my Projectable properties and methods? +Yes you can! Any projectable property/method can call into other properties and methods as long as those properties/methods are native to EFCore or as long as they are marked with a `Projectable` attribute. + +#### Can I use projectable extensions methods on non-entity types? +Yes you can. It's perfectly acceptable to have the following code: +```csharp +[Projectable]s +public static int Squared(this int i) => i * i; +``` +Any call to squared given any int will perfertly translate to SQL. + +#### How does this relate to [Expressionify](https://github.com/ClaveConsulting/Expressionify)? +Expressionify is a project that was launched before this project. It has some overlapping features and uses similar approaches. When I first published this project, I was not aware of its existance so shame on me. Currently Expressionify targets a more focusses scope of what this project is doing and thereby it seems to be more limiting in its capabilities. Check them out though! + +#### How does this relate to LinqKit/LinqExpander/...? +There are a few projects like [LinqKit](https://github.com/scottksmith95/LINQKit) that were created before we had code generators in dotnet. These are great options if you're stuck with classical EF or don't want to rely on code generation. Otherwise I would suggest that EntityFrameworkCore.Projections and Expresssionify are superior approaches as they are able to rely on SourceGenerators to do most of the hard work. + +#### Is the available for EFCore 3.1, 5 and 6? +Yes it is! there is no difference between any of these versions and you can upgrade/downgrade whenever you want. + +#### What is next for this project? +TBD... \ No newline at end of file diff --git a/samples/ReadmeSample/ApplicationDbContext.cs b/samples/ReadmeSample/ApplicationDbContext.cs new file mode 100644 index 0000000..9b690da --- /dev/null +++ b/samples/ReadmeSample/ApplicationDbContext.cs @@ -0,0 +1,31 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Security.Cryptography.X509Certificates; +using System.Text; +using System.Threading.Tasks; +using EntityFrameworkCore.Projections.Extensions; +using Microsoft.EntityFrameworkCore; +using ReadmeSample.Entities; + +namespace ReadmeSample +{ + public class ApplicationDbContext : DbContext + { + public DbSet Users { get; set; } + public DbSet Products { get; set; } + public DbSet Orders { get; set; } + + protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) + { + optionsBuilder.UseSqlServer("Server=(localdb)\\MSSQLLocalDB;Database=ReadmeSample;Trusted_Connection=True"); + optionsBuilder.UseProjections(); + } + + protected override void OnModelCreating(ModelBuilder modelBuilder) + { + modelBuilder.Entity().HasKey(x => new { x.OrderId, x.ProductId }); + } + + } +} diff --git a/samples/ReadmeSample/Entities/Order.cs b/samples/ReadmeSample/Entities/Order.cs new file mode 100644 index 0000000..6a48a79 --- /dev/null +++ b/samples/ReadmeSample/Entities/Order.cs @@ -0,0 +1,25 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using EntityFrameworkCore.Projections; + +namespace ReadmeSample.Entities +{ + public class Order + { + public int Id { get; set; } + public int UserId { get; set; } + public DateTime CreatedDate { get; set; } + + public decimal TaxRate { get; set; } + + public User User { get; set; } + public ICollection Items { get; set; } + + [Projectable] public decimal Subtotal => Items.Sum(item => item.Product.ListPrice * item.Quantity); + [Projectable] public decimal Tax => Subtotal * TaxRate; + [Projectable] public decimal GrandTotal => Subtotal + Tax; + } +} diff --git a/samples/ReadmeSample/Entities/OrderItem.cs b/samples/ReadmeSample/Entities/OrderItem.cs new file mode 100644 index 0000000..a74b945 --- /dev/null +++ b/samples/ReadmeSample/Entities/OrderItem.cs @@ -0,0 +1,12 @@ +namespace ReadmeSample.Entities +{ + public class OrderItem + { + public int OrderId { get; set; } + public int ProductId { get; set; } + public int Quantity { get; set; } + + public Order Order { get; set; } + public Product Product { get; set; } + } +} diff --git a/samples/ReadmeSample/Entities/Product.cs b/samples/ReadmeSample/Entities/Product.cs new file mode 100644 index 0000000..488213b --- /dev/null +++ b/samples/ReadmeSample/Entities/Product.cs @@ -0,0 +1,11 @@ +namespace ReadmeSample.Entities +{ + public class Product + { + public int Id { get; set; } + + public string Name { get; set; } + + public decimal ListPrice { get; set; } + } +} diff --git a/samples/ReadmeSample/Entities/User.cs b/samples/ReadmeSample/Entities/User.cs new file mode 100644 index 0000000..596c161 --- /dev/null +++ b/samples/ReadmeSample/Entities/User.cs @@ -0,0 +1,16 @@ +using System.Collections; +using System.Collections.Generic; + +namespace ReadmeSample.Entities +{ + public class User + { + public int Id { get; set; } + + public string UserName { get; set; } + + public string EmailAddress { get; set; } + + public ICollection Orders { get; set; } + } +} diff --git a/samples/ReadmeSample/Extensions/UserExtensions.cs b/samples/ReadmeSample/Extensions/UserExtensions.cs new file mode 100644 index 0000000..5b41d0d --- /dev/null +++ b/samples/ReadmeSample/Extensions/UserExtensions.cs @@ -0,0 +1,17 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using EntityFrameworkCore.Projections; +using ReadmeSample.Entities; + +namespace ReadmeSample.Extensions +{ + public static class UserExtensions + { + [Projectable] + public static Order GetMostRecentOrderForUser(this User user, DateTime? cutoffDate) + => user.Orders.Where(x => x.CreatedDate >= cutoffDate).OrderByDescending(x => x.CreatedDate).FirstOrDefault(); + } +} diff --git a/samples/ReadmeSample/Program.cs b/samples/ReadmeSample/Program.cs new file mode 100644 index 0000000..0a718bb --- /dev/null +++ b/samples/ReadmeSample/Program.cs @@ -0,0 +1,49 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using Microsoft.EntityFrameworkCore; +using ReadmeSample.Entities; +using ReadmeSample.Extensions; + +namespace ReadmeSample +{ + class Program + { + static void Main(string[] args) + { + using var dbContext = new ApplicationDbContext(); + + // recreate database + dbContext.Database.EnsureDeleted(); + dbContext.Database.EnsureCreated(); + + // Populate with seed data + var sampleUser = new User { UserName = "Jon", EmailAddress = "jon@doe.com" }; + var sampleProduct = new Product { Name = "Blue Pen", ListPrice = 1.5m }; + var sampleOrder = new Order { + User = sampleUser, + TaxRate = .19m, + CreatedDate = DateTime.UtcNow, + Items = new List { + new OrderItem { Product = sampleProduct, Quantity = 5 } + } + }; + + dbContext.AddRange(sampleUser, sampleProduct, sampleOrder); + dbContext.SaveChanges(); + + // Lets try a query! + var query = dbContext.Users + .Where(x => x.UserName == "Jon") + .Select(x => new { + x.GetMostRecentOrderForUser(DateTime.UtcNow.AddDays(-30)).GrandTotal + }); + + var result = query.First(); + + Console.WriteLine($"Jons latest order had a grant total of {result.GrandTotal}"); + Console.WriteLine($"The following query was used to fetch the results:"); + Console.WriteLine(query.ToQueryString()); + } + } +} diff --git a/samples/ReadmeSample/ReadmeSample.csproj b/samples/ReadmeSample/ReadmeSample.csproj new file mode 100644 index 0000000..b9b76e2 --- /dev/null +++ b/samples/ReadmeSample/ReadmeSample.csproj @@ -0,0 +1,23 @@ + + + + Exe + net5.0 + disable + true + $(BaseIntermediateOutputPath)Generated + false + + + + + + + + + + + + + + diff --git a/src/EntityFrameworkCore.Projections.Generator/ProjectionExpressionGenerator.cs b/src/EntityFrameworkCore.Projections.Generator/ProjectionExpressionGenerator.cs index fab24cd..ae3dcdd 100644 --- a/src/EntityFrameworkCore.Projections.Generator/ProjectionExpressionGenerator.cs +++ b/src/EntityFrameworkCore.Projections.Generator/ProjectionExpressionGenerator.cs @@ -6,6 +6,7 @@ using System; using System.Collections.Generic; using System.Linq; using System.Text; +using System.Threading; using System.Threading.Tasks; namespace EntityFrameworkCore.Projections.Generator @@ -32,19 +33,29 @@ namespace EntityFrameworkCore.Projections.Generator { resultBuilder.Clear(); - foreach (var usingDirective in projectable.UsingDirectives) + foreach (var usingDirective in projectable.UsingDirectives.Distinct()) { resultBuilder.AppendLine(usingDirective); } - if (projectable.TargetClassNamespace is not null && !projectable.UsingDirectives.Contains(projectable.TargetClassNamespace)) + if (projectable.TargetClassNamespace is not null) { - resultBuilder.AppendLine($"using {projectable.TargetClassNamespace};"); + var targetClassUsingDirective = $"using {projectable.TargetClassNamespace};"; + + if (!projectable.UsingDirectives.Contains(targetClassUsingDirective)) + { + resultBuilder.AppendLine(targetClassUsingDirective); + } } - if (projectable.ClassNamespace is not null && projectable.ClassNamespace != projectable.TargetClassNamespace && !projectable.UsingDirectives.Contains(projectable.ClassNamespace)) + if (projectable.ClassNamespace is not null && projectable.ClassNamespace != projectable.TargetClassNamespace) { - resultBuilder.AppendLine($"using {projectable.ClassNamespace};"); + var classUsingDirective = $"using {projectable.TargetClassNamespace};"; + + if (!projectable.UsingDirectives.Contains(classUsingDirective)) + { + resultBuilder.AppendLine(classUsingDirective); + } } var generatedClassName = ProjectionExpressionClassNameGenerator.GenerateName(projectable.ClassNamespace, projectable.NestedInClassNames, projectable.MemberName); diff --git a/tests/EntityFrameworkCore.Projections.Generator.Tests/ProjectionExpressionGeneratorTests.ProjectableExtensionMethod2.verified.txt b/tests/EntityFrameworkCore.Projections.Generator.Tests/ProjectionExpressionGeneratorTests.ProjectableExtensionMethod2.verified.txt index 10f8646..0adccb7 100644 --- a/tests/EntityFrameworkCore.Projections.Generator.Tests/ProjectionExpressionGeneratorTests.ProjectableExtensionMethod2.verified.txt +++ b/tests/EntityFrameworkCore.Projections.Generator.Tests/ProjectionExpressionGeneratorTests.ProjectableExtensionMethod2.verified.txt @@ -1,8 +1,6 @@ using System; using System.Linq; using EntityFrameworkCore.Projections; -using System; -using Foo; namespace EntityFrameworkCore.Projections.Generated #nullable disable