r/dotnet • • 8h ago

Promotion Learning to Implement JWT in .NET as a Beginner

22 Upvotes

Hey guys! I’m a beginner to web and .NET development, and here I share my learnings about JWT and how I implemented it in my .NET application.

I talked about access and refresh tokens, token rotation and revocation, and storage on both the client and the server.

You can read about it in more detail here:

https://paoloragudo.com/blog/posts/learning-to-implement-jwt-in-net

Questions, comments, and suggestions are welcome!

No AI has been used in writing the article

Edit: The expense tracker API part got less focus on, so I might have skipped implementation on a few things


r/dotnet • • 9h ago

Promotion I built a native WinUI 3 + .NET 10 Native AOT replacement for Microsoft To Do [v1.0]

Post image
24 Upvotes

Hey everyone,

I just published v1.0 of Wintodo to the Microsoft Store. I originally started building it for myself because Microsoft barely touched To Do for years, and now they announced they're shutting it down in June 2027 with no native replacement on Windows. I didn't want to move to an Electron or WebView2 app, so I went all in on WinUI 3, Windows App SDK 2.5.1, and .NET 10 Native AOT (x64 and ARM64).

The app mirrors the usual To Do workflow (My Day, Important, Planned, lists/groups, subtasks, recurrence, attachments, full keyboard nav, Ctrl+Z undo), plus a read-only Microsoft Graph importer so you can pull your existing lists out of To Do without touching them. Everything lives locally in SQLite by default, or syncs over standard CalDAV (VTODO, tested with Nextcloud Tasks, Radicale, Fastmail) and .ics import/export.

Keeping the whole thing Native AOT clean was the main constraint from day one. That meant skipping EF Core and reflection-based JSON completely, using raw SQLite + FTS5 with hand-written mappers, and writing our own RFC 5545 VTODO/RRULE parser and CalDAV client. For the UI, I paired compiled {x:Bind} templates with a custom IObservableVector + SequenceDiff so sorting and filtering don't thrash the ListView. Reminders go straight through ScheduledToastNotification, so they still fire when the app is closed without needing a background process.

I profiled the Store x64 build side-by-side against the UWP Microsoft To Do app just to see how WinUI 3 + Native AOT holds up:

  • 86.8 MB private working set in Task Manager (182.2 MB total WS vs. 200.0 MB in To Do), 1 process, 18 threads vs. 32 in To Do
  • 56.6 MiB self-contained MSIX on x64 (55.0 MiB on ARM64), 21.3 MiB native Wintodo.exe
  • 119.37 fps scrolling 10,000 tasks in a single list (0 dropped frames on a 120 Hz screen)
  • 1.5-2.7 ms smart-list queries and 2.3-6.7 ms FTS5 search on 10k tasks; going from 0 to 20k tasks adds ~38 MB RAM

The app is free on the Store with no ads or telemetry, and the code is on GitHub under a source-available license (not OSI open source, just being upfront). If there's demand later I might add an optional paid cloud sync on our own infra, while keeping local SQLite and bring-your-own CalDAV free.

Curious to hear what people think, especially if anyone else here is shipping WinUI 3 + Native AOT apps to the Store.


r/dotnet • • 12h ago

Promotion NETworkManager 2026.11.15.0 – a free, open-source network toolbox for Windows: RDP, SSH, PowerShell, VNC, IP/Port Scanner, Traceroute, DNS and more in one app

Post image
40 Upvotes

Hi, I'm the developer of NETworkManager, a free, open-source app for Windows that puts the tools you need to manage and troubleshoot networks into one place, so you don't have to juggle a dozen small utilities.

What it does

  • Remote access: Remote Desktop, SSH/Telnet/Serial (via PuTTY), PowerShell and VNC, embedded in tabs you can drag out into their own windows
  • Scanning & monitoring: IP Scanner, Port Scanner, Ping Monitor, Traceroute
  • Lookups: DNS, Whois, RDAP, IP geolocation, OUI/MAC vendor and ports
  • Network: WiFi Analyzer, LLDP/CDP capture, Network Interface (change IP/DNS settings), Neighbor Table, Firewall and Hosts File Editor
  • Profiles: save your hosts once (optionally encrypted), then connect to, ping or scan them from any tool

What's new in 2026.11.15.0

  • Complete UI redesign: new layout, new icon set, 7 new themes and 9 new accent colors
  • Run command (Ctrl+Shift+P): type ping 10.0.0.1, dns example.com aaaa, subnet 10.0.0.0/16 /24 or rdp @server-01 and it runs right away. It has suggestions and a global hotkey, so you can open it from anywhere.
  • Traceroute map: shows where each hop is located on an offline world map
  • RDAP: new tool for the modern, JSON-based successor to Whois (domains, IPs, ASNs)
  • WiFi Analyzer: highlights networks that are new, gone or changed since the last scan, with optional notifications
  • Faster scanners: IP and Port Scanner now use async concurrency
  • Better tabs: tabs size to their title, and dragged-out tabs can be dropped onto any other tab bar
  • ARM64 builds

Under the hood

Built with .NET 10 and WPF, using MahApps.Metro with custom designs.

Free, GPLv3, no telemetry. Available as an installer, a portable version, and via WinGet and Chocolatey.

Feedback welcome! I'd love to hear what you think, especially which tool you're missing or what annoys you in your current workflow. Bug reports and feature requests are best opened as an issue on GitHub so they don't get lost, but I'll also read and answer comments here.


r/dotnet • • 19h ago

Article Moved my bots to .NET 11 for runtime async, the only scary part was /metrics

41 Upvotes

I've been waiting for runtime async for a long time so I moved my two Telegram bots to .NET 11 pretty much right after release. Got it working the same day, nothing dramatic. Tried runtime async on one of them and so far it's great, but I'm still too shy to turn it on in prod.

The one thing that got me is OpenTelemetry. Anything past 1.17 and /metrics just returns 200 with an empty body, no errors, health checks green, so it's really easy to miss. Pinned it to 1.17 for now. The thread pool metrics also lost the _total suffix so old dashboards go quiet too.

Anyone running runtime async in prod already? Did anything blow up?


r/dotnet • • 1h ago

Promotion One year later: .NET MAUI camera updated in App Store and Google Play

1 Upvotes

Hey all, after almost a year Filters Camera (a .NET MAUI app) hit a new big update in both App Store and Google Play!

Here’s the old post about how this all started, mainly as a “let’s see the FPS it can do” challenge, an Android and iOS MAUI app completely drawn on a single SkiaSharp view:
reddit.com/r/dotnet/comments/1n8441e/published_net_9_crossplatform_camera_app_maui

What began as an open-source experiment evolved into a rather solid .NET 10 app, now with video recording, lighting effects, image adjusting/cropping/healing, and some nice shaders if I may say so. I also added optional IAP and analytics.
filterscamera.app

You may have seen MAUI Blazor hybrids, here we deal with a “drawn MAUI hybrid” which uses the richness of MAUI and its ecosystem together with SkiaSharp / Google Skia (big thanks to all of them).

I’ve spent a lot of time improving this app, and this work has also pushed DrawnUI, a package you can plug into existing apps and frameworks that lets you work on a Skia canvas with a lot of power, and it ships with AI skills for a faster development.

My camera NuGet for MAUI package has also progressed due to working on this app, solving Android 16 KB page alignment, dealing with several iOS updates (on basically every one of them the camera got a new bug). On the latest one (iOS 27), the preview was showing in landscape instead of portrait but I got lucky that a user emailed me about it, and I was able to fix it the same day.

The before-after web widget you might see on the app landing page is also built completely with DrawnUI and hosted on its fiddle. By the way, I reused the stroke animated gradient created there by the awesome designer of Horus Studio and you can see it inside the app in the Premium area. This also led to creating a nice celebration shader for the Settings → Credits page.

In a month or so the app should go .NET 11, right? :)


r/dotnet • • 1d ago

I want the old development stuff

65 Upvotes

Programming was fun, until AI ruins it, there were many programming stacks and tools to choose from, everything has pros and cons, problems solving after frustration or finding the answer on that 15 yo post on stackoverflow asking the same question as yours or running on extreme edge cases and utilizing documentation then problem solved, bingo dopamine hits I miss that .

now almost everything is an AI slop or weird random geek dude bragging about some vibecoded project that has almost no use in real world .

there's niche hobby of mine that's still unexplored e.g. making a homebrew games or porting tools from language to the other but still the argument about which programming stack is better and the discussion about it was part of the fun now they're talking about prompt engineering or some BS crab , can anyone git restore what the industry heading towards ?


r/dotnet • • 2h ago

Modular monolithic vs. microservices architecture from my own experience

Thumbnail reddit.com
0 Upvotes

r/dotnet • • 1d ago

Promotion OpenSilver adds native scrolling, making it the smoothest-scrolling XAML framework on the web

15 Upvotes

Hi everyone,

We just added native scrolling to the OpenSilver 3.4 Preview. ScrollViewer and virtualized lists now let the browser do the scrolling itself, which makes OpenSilver by far the smoothest-scrolling XAML framework on the web.

On desktop the difference is hard to see, because desktop computers are fast enough to hide it. On mobile, and especially on low-end phones, it's striking. To compare, we built the same app with the three major .NET cross-platform UI frameworks that run on the web:

The source code is here: https://github.com/OpenSilver/ScrollingPerformanceBenchmark

Be sure to try them on your phone. That's where the difference really shows.

Performance isn't the only benefit. Because the browser does the scrolling, you also get:

  • Ctrl+F that scrolls to the results, even inside scrollable areas
  • Native scrollbars on mobile and macOS (optional), which look and behave like the platform's own
  • Better accessibility: screen readers and other assistive tools can recognize real browser scroll containers and scroll them
  • Browser extensions support (change fonts, dark mode, translate...)
  • Auto-scrolling while selecting text, when you drag past the edge of a scrollable area
  • Native touch and momentum scrolling, with the inertia and edge bounce / overscroll effects users expect on their device

This is possible because OpenSilver renders the UI as real HTML elements, while the other .NET UI frameworks that run in the browser draw into a canvas.

Existing OpenSilver apps don't need any code changes. The Silverlight/WPF ScrollViewer API stays the same, and native scrolling is on by default. If something doesn't work as expected, you can turn it off for the whole app or for a single ScrollViewer.

This is part of our goal of making OpenSilver the "web-native WPF". We'd love your feedback: try it on your own apps, and please report anything that behaves differently on GitHub: https://github.com/OpenSilver/opensilver

Happy to answer any questions!


r/dotnet • • 1d ago

Promotion I created a Source Generator for creating Non-Boxing Unions in .NET 11

50 Upvotes

[NOTE: I am still working on uploading it to nuget.org, but I wanted to share this here so anyone that's interested can look at the source code behind it]

Default unions in .NET 11 will always box value types. This is an unfortunate (though understandable) part of the release of unions with .NET 11.

I created a NuGet package which provides a simple attribute and a source generator to handle the slightly tedious boilerplate of making a non-boxing union.

A quick example of how to use the package after installing it:

using NonBoxingUnions;

[NonBoxingUnion<int, double, float>]
public partial struct MyUnion;

// or, you can use the `params Type[]` ctor:

[NonBoxingUnion(typeof(int), typeof(double), typeof(float)]
public partial struct MyUnion

This package provides 17 attributes: 1 non-generic attribute with a ctor that takes in a params Type[] value, allowing infinite types, and 16 generic attributes to allow anywhere from 1-16 types through generics.

You can view the source code at https://github.com/nathandavis18/Non-Boxing-Unions. It is really a simple generator, around 400 lines of code is all it takes to allow creating non-boxing unions anywhere you want.

EDIT: The package is published and available for use from nuget.org: https://www.nuget.org/packages/NonBoxingUnions.Generator


r/dotnet • • 21h ago

Promotion BouncyHsm 2.4.0 now with Aspire

Thumbnail github.com
5 Upvotes

Hello,

I’m launching a new version of BouncyHsm. It’s a simulator of a hardware cryptographic key storage device accessible via the PKCS#11 interface, with a REST API for management, a web interface and a CLI. It’s mainly used in the development of applications that utilise HSMs or smart cards.

Key new features include over 100 bug fixes in edge cases, as well as support for the Aspire 17 (with new docker image).

Aspire example:

var bouncyHsm = builder.AddBouncyHsm("bouncyhsm")
    .WithStorage(storage: BouncyHsmStorage.InMemory) // InMemory or LiteDbInVolume with mount volume
    .WithHsmSlotAndToken(slotDescription: "Slot1", tokenLabel: "oper1", userPin: "123456", soPin: "12345678") // crate a new slot after start
        .WithImportPkcs12(tokenLabel: "oper1",
            pkcs12Content: TestData.GenerateP12(), password: "password",
            ckaId: Encoding.UTF8.GetBytes("SigningCertificate"), ckaLabel: "SigningCertificate") // import P12 file as private key, public key and certificate
    .WithHsmSlotAndToken(slotDescription: "Slot2", tokenLabel: "oper2", userPin: "123456", soPin: "12345678")
        .WithImportPemObjects(tokenLabel: "oper2",
            pem: aesKeyPem,
            ckaId: Encoding.UTF8.GetBytes("AES-key"), ckaLabel: "AES-key",
            hints: BouncyHsmPemHint.ForEncryption | BouncyHsmPemHint.ForWrap); // import PEM objects

builder.AddDotnetProject("exampleapi", "../ExampleApi/ExampleApi.csproj")
     .WaitForStart(bouncyHsm)
     .WithBouncyHsmApiReference(bouncyHsm) // reference HTTP endpoint for BouncyHSM API
     .WithBouncyHsmNativeLibEndpointReference(bouncyHsm, BouncyHsmLogTarget.NONE, BouncyHsmLogLevel.NONE, tag: "exampleapi"); // reference environment variable from PKCS#11 native library

I’ve been working on the project since 2022. I don’t primarily use code generation, but I don’t reject pull requests created by AI. Since the last release, I’ve started to see AI-generated issues highlighting deviations from the standard, so I had AI Copilot carry out a code review and then assessed each finding against the code and the standard.

There were over a hundred findings. Approximately 80% were relevant (last year, only 20% were relevant), of which 90% were fixes to one or two lines of code, and 90% of the problems found were edge cases that a normal developer working with PKCS#11 would not encounter.


r/dotnet • • 1d ago

Article Minimize your CI time in .NET Projects with dotnet-affected

Thumbnail stenbrinke.nl
62 Upvotes

r/dotnet • • 21h ago

Promotion nanoql: a stateless quantitative finance library for .NET 10, derived from QuantLib and checked against it

4 Upvotes

nanoql is an open-source pricing library for .NET 10: curves, swaps, swaptions, SABR, equity options, Heston, CDS. Instruments, curves and models are immutable values, and pricers are static functions of them; the evaluation date is an argument, not a global setting.

var today = new Date(15, Month.October, 2026);
var context = new EvaluationContext { EvaluationDate = today };
var curve = new FlatForward(today, 0.036, new Actual365Fixed());

var swap = new MakeOIS(new Period(5, TimeUnit.Years), new Sofr(curve))
    .WithFixedRate(0.036).WithNominal(10e6)
    .ToOvernightIndexedSwap(context);

var result = DiscountingSwapEngine.Calculate(swap, context, curve);
Console.WriteLine($"NPV {result.NPV:N2}, fair rate {result.FairRate:P4}");
// NPV 7,041.24, fair rate 3.6154%

Some .NET details that may interest you:

  • It targets .NET 10, the current LTS; static abstract interface members rule out a .NET Framework build.
  • Python, C and C++ reach it through Native AOT: one C interface over the compiled library, so pip install nanoql needs no .NET runtime.
  • The Excel add-in is generated from the same surface with Excel-DNA.
  • It's derived from QuantLib 1.44 and checked against it: 3.35 million reference outputs, 99.86% within a relative 1e-10, and QuantLib's own tests ported at their tolerances.

dotnet add package NanoQL · getting started · GitHub · Apache-2.0


r/dotnet • • 13h ago

Promotion TodoForge 1.2.0: a free VS Code TODO tree for .NET repos, now with relative due dates and bulk actions

1 Upvotes

I'm a C# / .NET developer. I wrote a free, MIT-licensed VS Code extension called TodoForge, and 1.2.0 just went out.

The problem I kept hitting in large .NET solutions was not "find the word TODO". It was knowing which TODOs I had just added on a feature branch, which ones were mine, and which were already overdue, without noise from bin/, obj/ or generated files.

You can put an owner, a due date, a priority and a label in the comment itself:

// TODO(onur, 2026-12-01, !high, #perf): cache the price lookup
// FIXME(@ayse): null check before Save()

New in 1.2.0:

- Relative due dates: write `TODO(me, +7d)`, `+2w`, `tomorrow` or `friday` and a quick fix turns it into a fixed ISO date, so the comment stays stable.
- Bulk actions: select several TODOs in the tree and snooze, set a due date, set priority, assign or pin them all at once (one undo step).
- The tree shows up instantly after a reload (the last scan is cached locally), then refreshes in the background.
- Only changed rows redraw, so selection and scroll stay put while you edit.
- Smaller download: a platform-specific package of about 2–3 MB instead of about 15 MB.

A few .NET-specific bits that were already there:

- bin/, obj/, packages, *.g.cs, *.designer.cs and minified files are skipped by default, and .gitignore is honored.
- In C# it also lists throw new NotImplementedException(), [Obsolete] and #warning in their own view.
- A Changes view, fed only by local git, shows TODOs added on your branch, which is the check I wanted before opening a PR.
- Import Settings reads Visual Studio .vssettings and Rider .DotSettings task tokens.

It's offline: no account, no telemetry, no network calls. English and Turkish UI.

Marketplace: https://marketplace.visualstudio.com/items?itemName=onurkarakus.todoforge
Open VSX: https://open-vsx.org/extension/onurkarakus/todoforge
GitHub: https://github.com/onurkarakus/todo-forge

If you try it on a real solution and something is noisy or missing, I'd like to know.


r/dotnet • • 17h ago

Promotion I'm building my own video and music player based on libmpv2 with Avalonia UI (Linux only)

Thumbnail gallery
1 Upvotes

r/dotnet • • 12h ago

[Show & Tell] eQuantic.UI: Write UI components once in C# and compile to vanilla JS (no WASM) on the web or native GPU pixels via Metal/Vulkan (no WebView/Skia)

Thumbnail reddit.com
0 Upvotes

r/dotnet • • 21h ago

Question Follow-up to my tenant isolation question: I made the build fail if anyone bypasses EF Core query filters

1 Upvotes

A few days ago I asked how you stop someone calling IgnoreQueryFilters() in a multi-tenant app. Thanks to everyone who answered; a lot of you said "turn the rule into a check, not a guideline."

Here's the first layer I added: an architecture test that scans the source and fails if it finds a bypass.

public class QueryFilterGuardTests

{

private static readonly string[] Forbidden =

{ "IgnoreQueryFilters", "FromSql", "ExecuteSql" };

[Fact]

public void Source_Code_Never_Bypasses_Tenant_Filters_Or_Uses_Raw_Sql()

{

var src = Path.Combine(RepoLocator.FindRoot(), "src");

var sep = Path.DirectorySeparatorChar;

var offences = Directory

.EnumerateFiles(src, "*.cs", SearchOption.AllDirectories)

.Where(p => !p.Contains($"{sep}obj{sep}")

&& !p.Contains($"{sep}bin{sep}")

&& !p.Contains($"{sep}Migrations{sep}"))

.SelectMany(p => File.ReadLines(p)

.Select((line, i) => (p, line, n: i + 1)))

.Where(x => Forbidden.Any(w => x.line.Contains(w)))

.Select(x => $"{Path.GetRelativePath(src, x.p)}:{x.n} -> {x.line.Trim()}")

.ToList();

Assert.True(offences.Count == 0,

"Forbidden calls found:\n" + string.Join("\n", offences));

}

}

Alongside it, I have isolation tests on real PostgreSQL (not in-memory) that seed two tenants and check that tenant A can't read, load by ID, or write tenant B's data.

What I know it doesn't cover (some of you pointed this out):

  • It's a text match, so reflection or a creative workaround gets past it
  • It's not a Roslyn analyzer, so you only find out at test time, not in the IDE
  • The real backstop is Postgres RLS, which I'm working on next

Two questions:

  1. Is a Roslyn analyzer worth it over this for a small team, or is the test enough?
  2. For RLS with connection pooling, do you set app.tenant_id in a DbConnectionInterceptor or per transaction?

r/dotnet • • 1d ago

Promotion EF Core Query Plan Visualizer Ported to VS Code: EFCore Visualizer 1.0

Thumbnail giorgi.dev
45 Upvotes

r/dotnet • • 1d ago

Promotion Injectify v1.0 attribute-based service registration for Microsoft.Extensions.DependencyInjection

Post image
17 Upvotes

Hi r/dotnet,

I've been working on a small .NET library called Injectify. It's now at version 1.0.5 on NuGet, and this is the first time I'm sharing it here.

The idea came from wanting to reduce the repetitive dependency registration code that often accumulates in Program.cs (AddScoped, AddSingleton, AddTransient, etc.).

With Injectify, you can declare service lifetimes directly on classes using attributes like [Scoped], [Singleton], and [Transient], then register everything from an assembly with a single call.

It also includes DrawAggregator, which generates Mermaid dependency graphs from annotated classes, making it easier to visualize constructor dependencies.

The library is lightweight and has no external dependencies.

GitHub: https://github.com/Roma1011/Injectify

NuGet: https://www.nuget.org/packages/Injectify.Auto

I'd love to hear your feedback. Would you consider using attribute-based DI registration in your projects, or do you prefer keeping registrations explicit in Program.cs?

Thanks!


r/dotnet • • 22h ago

AnyCLI - an AoT-friendly library for building modern CLI apps in C#/.NET

Thumbnail drmathias.github.io
0 Upvotes

r/dotnet • • 19h ago

Promotion I implemented LINQ in my own programming language!

Post image
0 Upvotes

I've been working on my own scripting language for my game engine, whose interpreter I wrote in C#. So, for quite a long time now, the only languages I use are C# and my custom language.

Apparently, Earth is a really dark and sad place without LINQ, so I decided to add it to my language!

My language's LINQ library source code

I did my best to make the design as close to .NET LINQ as possible. You can query anything that you can use in a foreach loop, and it uses deferred execution, meaning the query doesn't actually run until you iterate over it or call .toArr(), .toList(), or one of the other methods that execute it.

It also performs just one iteration per query. You can do where().select(), and instead of iterating once for the where operator and then again for the select operator, it processes both in a single iteration.

I had to figure out how to achieve this in a language that doesn't have the yield return keyword. I know theoretically what yield return does, but actually figuring out how to get the same result without using it was quite challenging...

Anyway, you can see a few examples of queries written in my language in the screenshot.

The syntax isn't as clean as C#'s, but it's good enough for me!

Here's another little example:

class User (name, password) { constructor(...); }

const users =
[
    new User("Peter", "messithegoat"),
    new User("Donald", "london101"),
    new User("Joe", "banana1234"),
    new User("Ben", "chocolate2")
]

foreach user in q(users).orderBy(func(u) => u.name, StringComparer.ordinalIgnoreCase)
{
    println(user.name)
}

// Output:
> Ben
> Donald
> Joe
> Peter

And here you can see the full code of the LINQ library written in my language. It's still missing some of the operators, but I've opened an issue in the repo for implementing the rest, so feel free to give it a try!

I've already had some contributions to other parts of the engine from people who thought the project was cool.


r/dotnet • • 1d ago

Promotion .NET 10 control plane with EF Core and PostgreSQL, looking for contributors to implement an OpenAPI draft

0 Upvotes

Waylorn is an AGPL-3.0 control plane for industrial infrastructure. The backend is .NET 10 minimal APIs with EF Core and PostgreSQL, with a Rust safety gate and a Next.js and Expo front end.

The front end is built against a draft OpenAPI contract, and the .NET API doesn't implement all of it yet. Missing routes include approvals, command preflight, audit search, asset reliability and events. I've split these into small issues labelled good first issue.

I'd especially value review of the endpoint structure, concurrency handling (assets use a version field) and test layout. The repo has a test project for HTTP and domain tests.

Disclosure: AI-assisted development, human-reviewed.

Repo: https://github.com/AbdulNafaySarmad1/Waylorn


r/dotnet • • 1d ago

Question Are there any options in dotnet for an embedded/local file database that support collections (particularly Dictionaries) and at most only require minimal changes to class structure?

7 Upvotes

Apologies if this question is too vague, please let me know if further clarification is needed.

I commonly encounter situations where I need to take some new JSON structure I haven't encountered before (which I did not create), deserialize it into a dotnet script, and then work with the data for a week or two. Since it is cumbersome to have to keep writing out json every time I run the program, and deserializing JSON can get very slow depending on size (on a few instances, I've had ~10GB json files to work with).

At this point, the initial deserialization has gotten easier, thanks to IDEs having the option to paste JSON as classes (still requires some light fixing afterwards, but it's manageable), but I've still yet to find a good ORM/database option for my needs. In particular, no built-in handling (or limited built-in handling) for collections has been the biggest problem.

Almost every data structure I work with involves having a class that contains arrays, and/or a dictionary, often with the array or dictionary value being another class. Outside of that, though, all the types within each class are generally all primitive types and strings.

I used LiteDB for a while, but that handles any sort of nesting by just storing the entire collection as an entire bson. For one, this has led to situations where LiteDB is extremely slow. This also results in situations where it's not possible to store the structure as-is, because the object is larger than LiteDB allows size-wise for bson documents.

After that, out of a few options I tried, the most noteworthy were SQLite mapping packages, but those didn't work very well, and were often out of date.

Finally, recently I've been trying to use EFCore with an SQLite database provider. Unfortunately, EFCore currently has no support for dictionaries, and the only workaround that's even somewhat manageable is to create a class with the key and value types i want, and then change each dictionary to be a list of that class. EFCore also requires me to pull my database using a .Include() for every single nested property, which can get cumbersome if I have a lot of collections or nesting.

Tl;dr all I really want is something I can store the classes/objects I parse from JSON into a local database file, that handles collections like arrays and dictionaries. Are there any options for this at the current moment? Included a few sample classes in the comments, if it helps.

Edit: It seems that what I'm looking for doesn't exist, since the use case where it's not worth making a proper database schema is fairly limited. That's more or less what I expected, I just wanted to make this post to make sure. Thanks to everyone for the replies!


r/dotnet • • 1d ago

Introducing SqlSource: generate models and repository classes from your SQL queries

0 Upvotes

tl;dr:

  1. Keep your queries in sql files. They don't clutter up your code, they work better with SQL editors, and with SQL linters and formatters.
  2. Use the dotnet sqlsource tool to generate sidecar files that describe the type information of the query parameters and results. The tool can be run in watch mode, or it can run automatically when you build.
  3. The SqlSource source generator creates models and methods the next time you build.
  • Github Project
  • Full Documentation
  • MIT Licensed
  • Supports .Net 8+ (but must compile using the .Net 9 SDK)
  • Supports PostgreSQL 14+ and SQL Server 2017+ (MySQL and SQLite coming before v1.0, I hope)

I've always been a bit annoyed by SQL queries in C# code. SqlSource began as a project to move them into their own files, but as I began working with source generators I started to realize that much, much more was possible. In its default mode, SqlSource now creates models and repositories for you. The generated code is essentially the same ADO.Net that you'd write by hand, so there's no performance overhead. Some of the other features available include:

  • Generate methods that take your own connection, transaction, and command timeout; for example when you want to write a public repository method that runs several queries in a transaction.
  • Generate queries as DbConnection extension methods if you don't care for the repository class structure.
  • Generate only models, with your queries as string constants, for projects already committed to using Dapper.
  • Type information AND nullability are read from your database; properties are only non-null when confirmed by the database (can be overridden).
  • Sync and async method generation.
  • Supports binding json columns to strongly typed objects.
  • Built-in support for NodaTime and NetTopologySuite types.
  • Supports custom type conversions via simple static methods, for strongly typed id's, domain types, etc.
  • IAsyncEnumerable support for streaming large result sets.
  • Supports using collections with IN, i.e. Id IN @Ids.
  • Collection methods, i.e. insert/update a list of items, that automatically run in batches instead of making a db call for each item. This is about 5x faster on small collections (10 items) and 10x faster for large collections (1000+ items).
  • The generated code uses shared array pools for accumulating the results of queries up to 1024 items. This reduces allocations by ~25% vs simply using List<T>.
  • A token replacement mechanism as an escape hatch for the parts of queries that don't work with parameters, e.g. ORDER BY {{column}}.
  • A templater plugin for the SQLFluff linter/formatter, so it can parse the SqlSource token syntax.
  • A check option in dotnet sqlsource so your CI can verify that the sidecar files describing your queries are up to date.

Disclaimer: This library was written using AI tools under the direction and review of an engineer with 20 YoE. If that's a dealbreaker for you, well now you know.


r/dotnet • • 1d ago

Promotion I made a Global Warming Index windows app for a hackathon! I used c# while a friend did python in the backend any comments or suggestions how we could of implemented this better would be appreciated

Thumbnail github.com
0 Upvotes