Skip to content

arika0093/Linqraft

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Linqraft

NuGet Version GitHub Actions Workflow Status DeepWiki

Write Select queries easily with on-demand DTO generation and null-propagation operators. No dependencies.

Web Page | Online Playground

Features

Overview

Linqraft is a Roslyn Source Generator for easily writing IQueryable projections.

  • Query-based automatic DTO generation
    • You can freely define DTO structures in the query without predefining them.
    • Based on anonymous types, "what you see is what you get" declarations.
    • Supports nested DTOs, collections, and calculated fields.
  • Null-propagation operator support (?.) in Expression Trees
    • No more need to write o.Customer != null ? o.Customer.Name : null.
  • Zero-dependency
    • No runtime dependencies are required since it uses Source Generators and Interceptors.

With Linqraft, you can write queries like this:

var orders = await dbContext.Orders
    // Order: input entity type
    // OrderDto: output DTO type (auto-generated)
    .SelectExpr<Order, OrderDto>(o => new
    {
        // can use inferred member names
        o.Id,
        // null-propagation supported
        // you can create flattened structures easily
        CustomerName = o.Customer?.Name,
        // also works for nested objects
        CustomerCountry = o.Customer?.Address?.Country?.Name,
        CustomerCity = o.Customer?.Address?.City?.Name,
        // you can use anonymous types inside. great for grouping
        CustomerInfo = new
        {
            Email = o.Customer?.EmailAddress,
            Phone = o.Customer?.PhoneNumber,
        },
        // calculated fields? no problem!
        LatestOrderDate = o.OrderItems.Max(oi => oi.OrderDate),
        TotalAmount = o.OrderItems.Sum(oi => oi.Quantity * oi.UnitPrice),
        // collections available
        Items = o.OrderItems.Select(oi => new
        {
            // of course, features work here too
            ProductName = oi.Product?.Name,
            oi.Quantity
        }),
    })
    .ToListAsync();

By specifying OrderDto as the generic parameter for SelectExpr, DTO types are generated automatically from the anonymous-type selector. That means you don't need to manually declare OrderDto or OrderItemDto.

for example, the generated code looks like this:

Generated code example
// <auto-generated>
// This file is auto-generated by Linqraft 
// </auto-generated>
#nullable enable
#pragma warning disable IDE0060
#pragma warning disable CS8601
#pragma warning disable CS8602
#pragma warning disable CS8603
#pragma warning disable CS8604
#pragma warning disable CS8618
using System;
using System.Linq;
using System.Collections.Generic;
namespace Linqraft
{
    file static partial class GeneratedExpression
    {
        [global::System.Runtime.CompilerServices.InterceptsLocationAttribute(1, "HWIj1D9ydZTCzRj7o0y/oYkBAABUdXRvcmlhbENhc2VUZXN0LmNz")]
        public static IQueryable<TResult> SelectExpr_CE7A5A7D_5A34E201<TIn, TResult>(
            this IQueryable<TIn> query, Func<TIn, object> selector)
        {
            var matchedQuery = query as object as IQueryable<global::Tutorial.Order>;
            var converted = matchedQuery.Select(o => new global::Tutorial.OrderDto
            {
                Id = o.Id,
                CustomerName = o.Customer != null ? (string?)o.Customer.Name : null,
                CustomerCountry = o.Customer != null && o.Customer.Address != null && o.Customer.Address.Country != null ? (string?)o.Customer.Address.Country.Name : null,
                CustomerCity = o.Customer != null && o.Customer.Address != null && o.Customer.Address.City != null ? (string?)o.Customer.Address.City.Name : null,
                CustomerInfo = new global::Tutorial.LinqraftGenerated_F1A64BF4.CustomerInfoDto
                {
                    Email = o.Customer != null ? (string?)o.Customer.EmailAddress : null,
                    Phone = o.Customer != null ? (string?)o.Customer.PhoneNumber : null
                },
                LatestOrderDate = o.OrderItems.Max(oi => oi.OrderDate),
                TotalAmount = o.OrderItems.Sum(oi => oi.Quantity * oi.UnitPrice),
                Items = o.OrderItems
                    .Select(oi => new global::Tutorial.LinqraftGenerated_DE33EA40.ItemsDto
                    {
                        ProductName = oi.Product != null ? (string?)oi.Product.Name : null,
                        Quantity = oi.Quantity
                    })
            });
            return converted as object as IQueryable<TResult>;
        }

    }
}
namespace Tutorial
{
    public partial class OrderDto
    {
        public required int Id { get; set; }
        public required string? CustomerName { get; set; }
        public required string? CustomerCountry { get; set; }
        public required string? CustomerCity { get; set; }
        public required global::Tutorial.LinqraftGenerated_F1A64BF4.CustomerInfoDto? CustomerInfo { get; set; }
        public required global::System.DateTime LatestOrderDate { get; set; }
        public required decimal TotalAmount { get; set; }
        public required global::System.Collections.Generic.IEnumerable<Tutorial.LinqraftGenerated_DE33EA40.ItemsDto> Items { get; set; }
    }
}
namespace Tutorial.LinqraftGenerated_DE33EA40
{
    [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)]
    [Linqraft.LinqraftAutoGeneratedDtoAttribute]
    public partial class ItemsDto
    {
        public required string? ProductName { get; set; }
        public required int Quantity { get; set; }
    }
}
namespace Tutorial.LinqraftGenerated_F1A64BF4
{
    [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)]
    [Linqraft.LinqraftAutoGeneratedDtoAttribute]
    public partial class CustomerInfoDto
    {
        public required string? Email { get; set; }
        public required string? Phone { get; set; }
    }
}

Interested? Try it out in the Playground!

Drop-in Replacement Analyzers

Analyzers are provided to replace existing Select code with Linqraft. The replacement is completed in an instant.

Quick Start

For detailed installation instructions, see the Installation Guide.

Prerequisites

This library requires following environment:

  • C# 12 or later (for interceptor feature)
  • One of the following versions (or later):
    • .NET 8.0.400
    • Visual Studio 2022 version 17.11

Installation

Install Linqraft from NuGet:

dotnet add package Linqraft

Basic Usage

Anonymous pattern

Use SelectExpr without generics to get an anonymous-type projection:

var orders = await dbContext.Orders
    .SelectExpr(o => new
    {
        Id = o.Id,
        CustomerName = o.Customer?.Name,
        // ...
    })
    .ToListAsync();

Explicit DTO pattern

Specify the generics to generate a DTO class:

var orders = await dbContext.Orders
    // Order: input entity type
    // OrderDto: output DTO type (auto-generated)
    .SelectExpr<Order, OrderDto>(o => new
    {
        Id = o.Id,
        CustomerName = o.Customer?.Name,
        // ...
    })
    .ToListAsync();

Pre-existing DTO pattern

Use your existing DTO classes:

var orders = await dbContext.Orders
    .SelectExpr(o => new OrderDto
    {
        Id = o.Id,
        CustomerName = o.Customer?.Name,
        // ...
    })
    .ToListAsync();

// your existing DTO class
public class OrderDto { /* ... */ }

For more usage patterns and examples, see the Usage Patterns Guide.

Documentation

Getting Started

Usage Guides

Performance & Comparison

Help

  • FAQ - Common questions
  • Analyzers - Code analyzers and fixes

Examples

Example projects are available in the examples folder:

License

This project is licensed under the Apache License 2.0.

About

Write Select queries easily with on-demand DTO generation and null-coalescing operators.

Topics

Resources

License

Stars

Watchers

Forks

Sponsor this project

 

Languages