Sr. Content Developer at Microsoft, working remotely in PA, TechBash conference organizer, former Microsoft MVP, Husband, Dad and Geek.
166049 stories
·
33 followers

AWS builds new paths from idea to app for developers

1 Share

In the early days of running Amazon.com, teams saw how hard and expensive it was to provision and manage infrastructure, and how much it pulled them away from building. AWS launched in 2006 to change that. It turned storage, message queues, and compute into building blocks any developer could reach through an API, so that anyone, even a student in a college dorm room, could access the same technology as the largest companies in the world. For twenty years, we’ve been removing the barriers between builders and what they want to build.

Along the way, those initial building blocks grew to include more than 200 services. Organizations asked us for more control over how they run their workloads, and our services and console evolved to meet the needs of the largest enterprises. Millions of production workloads now run on AWS, but the same breadth and depth that make AWS a great place to grow also means more to set up for developers who are just getting started with an idea. Every decision you have to make up front is time spent away from the idea that brings you here in the first place.

This year, we went back to the idea AWS started with. You show up here to build, so our job is to get you building right away, without compromising on depth, security, or pricing. More and more of that building happens with AI. Coding agents make it easy to start an app, and more developers are building agents of their own, so we shipped for both: tools that make it easier to build and deploy, and tools that make it easier to build, run, and safely contain the agents you create. In this post, we’ll cover the highlights of what we shipped in 2026 to help developers and their agents stay focused on building, including launches from today’s re:Invent keynote: the new AWS Amplify and shared Kiro Crew for Teams.

What we delivered for developers in 2026

Setup no longer comes before building

This year, we reimagined what it looks like to get started on AWS. You can sign up for AWS using your existing GitHub, Google, Apple, or Amazon account. When you sign up for a new account, we now create and manage an organization for you behind the scenes, with projects you can set up with one click and the ability to add teammates via email. We also shipped spend limits for projects, starting at $20 per month, so you can stay in control of what you spend. IAM role manager is enabled by default in accounts and available in supported service consoles so that you don’t have to think about permissions as you’re building. Everything you build runs in one Region, so that multi-Region is a capability that you grow into, rather than a default you have to accept.

Your coding agent now knows AWS

Developers want to use their preferred agent, rather than a vendor’s, so we built new tools to help you teach your agent about AWS. We launched Agent Toolkit for AWS, which gives your agent AWS skills and guardrails so it can build on AWS safely and effectively. The AWS Management Console added a prompt that gives everyone signing in a shortcut to connect their agent to their AWS account right away.

Signing up for an AWS account used to mean finding the sign up page yourself and setting up credentials before you could deploy. Now, your coding agent can open AWS sign-up for you, and once you finish in the browser, short-lived credentials go straight back to the agent so it can connect to your account right away.

Give agents more work, within limits you set

We also delivered new ways to build with and for agents, such as Kiro Web and Kiro for iOS and Android. We shipped Kiro Crew, a persistent development workspace designed to run complex, multi-step tasks. It runs on your own hardware, remembers your context across sessions, and keeps work moving while you’re away. We also introduced Kiro bots, persistent agents in Kiro Crew that have their own threads, memory, and workspace. They can help you with ongoing ownership of long-running work streams, like code reviews or issue triage.

If you’re building your own agents, Strands harness gives you a fully assembled, open source agent in one line of Python or TypeScript. Across six benchmarks, it cost 28% less in tokens than other popular harnesses running the same models. We also shipped Strands Box, which helps you sleep better at night by pairing operating system isolation with policies for what your agent is allowed to do, such as which files it can change or how often it can post to Slack.

Catch problems before they reach production

Agents are helping us write code faster than ever, so we delivered new ways for you to keep your code safe and correct. AWS Continuum for code vulnerabilities finds vulnerabilities in your code and produces patches for the ones it confirms are exploitable. Amazon Aurora DSQL supports foreign key constraints, so the database refuses any write that would leave a record pointing at data that no longer exists. We also shipped AWS Emulator, which emulates AWS for you locally, returning your AWS SDK and CLI calls in milliseconds, without an AWS account, AWS credentials, or a network connection. After installing AWS Emulator, you point AWS calls at it with environment variables. This example also unsets any variables that could supply real AWS credentials:

export AWS_ENDPOINT_URL=https://127.0.0.1:9297
export AWS_SHARED_CREDENTIALS_FILE=~/.aws/emulator/9297/emulator_credentials
export AWS_CONFIG_FILE=~/.aws/emulator/9297/config
export AWS_EC2_METADATA_DISABLED=true
export AWS_DISABLE_HOST_PREFIX_INJECTION=true
export AWS_REGION=us-east-1
export AWS_DEFAULT_REGION=us-east-1
unset AWS_ACCESS_KEY_ID AWS_SECRET_ACCESS_KEY AWS_SESSION_TOKEN AWS_PROFILE

Then you or your agent run AWS commands as normal:

$ aws sts get-caller-identity

AWS Emulator returns a response in milliseconds:

{ 
    "UserId": "AIDAH5I7GEMO7ADXNFAZU", 
    "Account": "000000000000", 
    "Arn": "arn:aws:iam::000000000000:user/emulator" 
}

Running your web server got easier

Until this year, putting a web app on AWS Lambda meant reshaping it to fit Lambda’s event model, where each execution environment handles one request at a time. Developers rewrote their servers as event handlers or added adapters, and they had to tune their billing models to avoid paying for I/O wait. AWS Lambda Web Functions runs the web server you already have, built with a framework like Express or Next.js, using the same code you run on your laptop. One command deploys it and returns a live HTTPS URL. Each environment handles up to 128 requests at once, and you pay for CPU while your code is working, so a request waiting on a database query consumes little CPU.

In this example, your Express.js server code deploys to Lambda Web Functions with no Lambda-specific adapters or wrappers needed.

import express from 'express';

const app = express();
const [host, port] = process.env.AWS_LAMBDA_HTTP_ENDPOINT.split(':');

app.get('/', (req, res) => {
  res.json({ message: 'Hello from Lambda Web Functions!' });
});

app.listen(port, host, () => {
  console.log(`Server running on port ${port}`);
});

But running a modern web app on AWS still meant assembling your own stack for all the components an application needs, like frontend hosting, database, and sign-in, until today.

What’s new for developers today

Today, we announced the new AWS Amplify, which takes an app from code to a live URL in under a minute. Amplify puts managed hosting, database, and auth in one place, so you can deploy a web app without learning AWS first.

You and your coding agent can deploy your app with aws amplifygen3 deploy or with a Git push. Amplify recognizes more than 15 frameworks and builds the app for you, setting up the permissions it needs along the way. Every app gets separate preview and production environments to start. If a release goes wrong, you or your agent can roll your site back to a previous deployment in one step. Amplify is built with agents in mind: its APIs describe themselves, and the Amplify skill gives agents tested ways to finish each task, so they retry less.

When your app needs to store data for your users, you or your agent can initialize a database and auth for your app with aws amplifygen3 local init --type fullstack. Run your backend locally with aws amplifygen3 local run so you can develop on your computer first, then deploy when the changes work. When you’re ready to deploy, you get separate databases for each environment, so test data stays separate from your production. The backend is powered by tools you already know and work with, like PostgreSQL, Better Auth, and PostgREST. It’s also serverless, which means you don’t have to pick instance sizes or manage any servers. When your app has no traffic, the backend goes to sleep, and the next request wakes it in seconds.

$ aws amplifygen3 deploy -e preview
→ Uploading files
✓ Files uploaded in 0.4 seconds

DeploymentID fmc8n1w0vn created in Environment preview!
    Visit: https://preview-66vy--habit-tracker.amplify.app
    → Queued...
    → In progress...
    ✓ Deployment succeeded!
✓ Backend READY on branch source-upload: 2 migrations applied; /health
answers 200 after 1s
✓ https://preview-66vy--habit-tracker.amplify.app answers 200 after 1s

Your Amplify costs stay predictable from your first deploy. The Basic plan is $0 per month with no time limit. When your app grows, flat-rate plans start at $20 per month, and if you opt into overages, they stop at a price cap that you set.

Once your app has users, the work around it grows. Bug reports come in, and every change needs a review before it ships. Today, we also announced shared Kiro Crew for Teams, which lets your team hand that ongoing work, along with new feature development, to a shared crew of agents. The crew turns the team’s feedback into skills anyone can inspect and refine, so that the team stays in control of what ships. We also announced that Kiro memories now follow you across clients and devices. Your next task starts from what Kiro already learned, whether you pick it up on another machine, in your browser, on your phone, or in Kiro Crew. 

Back to the dorm room

In 2006, AWS made it so that anyone, even a student in a college dorm room, could access the same building blocks as the largest companies in the world. A big idea could start with a single API call. Turning that call into a working app was still up to the developer, and as AWS grew, choosing and connecting the right blocks became a skill of its own.

This year, we worked on making that path to a working app easier for developers and their coding agents. Now, that college student can ask their coding agent to deploy their web app to AWS, and the agent can open AWS sign-up for them and pick up credentials as soon as they finish. Their first AWS account is preconfigured for them, and their agent can deploy the app to AWS Amplify in under a minute. When their idea takes off, their app is already on the same AWS that runs millions of production workloads, so there’s nothing to move or rebuild.

That’s our vision for the AWS we’re building, one where ease of use goes hand in hand with security and scalability. This year’s launches are creating new paths from idea to app on AWS, and we can’t wait to see what you build on them.

Tell us in the comments what you’re building and what you’d like to see next. Developer feedback shaped this year’s launches, and it will shape the next ones too.

Read the whole story
alvinashcraft
11 minutes ago
reply
Pennsylvania, USA
Share this story
Delete

Everything released in November 2026 for Azure Developer CLI

1 Share

Welcome to the November 2026 edition of the Azure Developer CLI (azd) release blog. This post covers releases 1.37.3, 1.38.0, 1.39.1, and 1.40.0. Have a question or feedback? Post it in the Azure Developer CLI discussions on GitHub.

Highlights:

  • The Microsoft Foundry extension is generally available. Set up, test, and deploy hosted agents with azd.
  • Package Logic Apps Standard projects, including custom code projects, with the new Azure Logic Apps Standard extension (preview).
  • Build extensions that provide infrastructure layers for resource generation and provisioning.
  • Use stable extension APIs for informational and warning messages from deployment hooks.
  • azd update now supports machine-wide Windows x64 MSI installations from an elevated terminal.
  • Get more consistent extension errors, workflow directories, and subprocess cancellation.

New features

🤖 Microsoft Foundry extension is generally available

The Microsoft Foundry extension bundle (microsoft.foundry) reached version 1.0 and is generally available. It brings hosted agent setup, local testing with Agent Inspector, and deployment to azd, keeping agent and deployment configuration alongside your code in azure.yaml. It requires azd 1.37.0 or later. To get started, run azd ext install microsoft.foundry, or read the Microsoft Foundry extension general availability announcement for a full walkthrough.

⚡ Azure Logic Apps Standard extension (preview)

The new Azure Logic Apps Standard extension (azure.logicappsstandard) packages Logic Apps Standard projects for deployment with azd. Install it with azd ext install azure.logicappsstandard, then set language: logicappsstandard and host: function on your service in azure.yaml. If your logic app includes a .NET custom code project, point the customCodeProject property at its .csproj file. Special thanks to Ronald Bosma (@ronaldbosma) for proposing, building, and partnering with the team over several months to bring this extension to its 0.1.0 release. [#8005]

🔌 Extension infrastructure and deployment messages

Extensions add commands and integrate with azd project and deployment workflows. These updates give extension authors additional infrastructure support and a stable contract for deployment messages.

  • Use extension-provided infrastructure layers to let extensions generate resources and handle provisioning. The upcoming Azure Resources extension builds on this support. [#10823]
  • Return structured informational and warning messages from service predeploy and postdeploy handlers using stable v1 extension APIs. The existing beta APIs remain available for compatibility. [#10936]

⚙ Updates on Windows

  • azd update now supports machine-wide Windows x64 MSI installations from an elevated terminal when both the installed and target versions are stable. Custom installation directories are preserved, and channel changes still require the MSI installer. [#10696]

🪲 Bugs fixed

Extension output and workflows

  • Write extension command errors as structured JSON to stderr when JSON output is selected, keeping stdout clear for command results. [#10861]
  • Honor a workflow step’s explicit --cwd instead of a parent working directory, preventing agent initialization from splitting project configuration across directories. [#10763]
  • Stop subprocesses consistently when a command is cancelled and show clearer cancellation errors for azd exec. [#10699]

Provisioning output

  • Distinguish Azure AI Hubs and AI Projects from other Machine Learning workspaces in provisioning output. Contributed by @huong8373tt-beep. [#10803]

Other changes

  • Show Awesome azd as the single template gallery in azd template selection. [#10956]
  • Update Azure management libraries, including Container Apps v5.0.0 and App Service v6.0.0. [#10895]
  • Update the bundled Bicep CLI to v0.49.2. [#10930]
  • Reduce telemetry collection by omitting unsupported or unmatched hook names and removing builder image and tag collection. [#10720]
  • Record bounded diagnostic information about dropped extension telemetry reports without recording rejected payload content. [#9783]

New docs

New and updated azd documentation on Microsoft Learn:

New templates

Community-authored templates help you get started faster, solve real-world scenarios, and showcase best practices for deploying solutions with Azure Developer CLI.

The Azure Developer CLI template gallery continues to grow with contributions from the community. Thank you!

🙋‍♀️ New to azd?

If you’re new to the Azure Developer CLI, azd is an open-source command-line tool that helps you get your application from your local development environment to Azure faster. It provides developer-friendly commands that map to key stages in your workflow, whether you’re working in the terminal, your editor, or continuous integration and delivery.

The post Everything released in November 2026 for Azure Developer CLI appeared first on Azure SDK Blog.

Read the whole story
alvinashcraft
12 minutes ago
reply
Pennsylvania, USA
Share this story
Delete

GIMP 3.3 Development Builds Add a Shape Tool Nearly 25 Years After the First Request

1 Share

GIMP 3.3 development builds can draw lines, rectangles, stars, and other shapes directly. Shapes created as vector layers remain editable. The request for a dedicated tool dates to 2001.

Key points

  • What happened: GIMP 3.3 development builds gained a dedicated tool for drawing lines, rectangles, stars, and other shapes directly.
  • Development history: A request from 2001 grew into a discussion about nondestructive editing. Vector layers arrived in GIMP 3.2.

Read the full article on Joho no Todai · Japanese original

Read the whole story
alvinashcraft
12 minutes ago
reply
Pennsylvania, USA
Share this story
Delete

AI Acceleration Controversies

1 Share
From: AIDailyBrief
Duration: 25:59
Views: 2,720

AI social media spent the holiday weekend arguing over handoverism, rumors of broken encryption, and claims of Claude sabotage. NLW breaks down the Dario Amodei response on handoverism, the RSA cracking rumors, and the accusations aimed at Claude. Also covered are Anthropic's shaky first week as a public company and the new essay calling for a speed limit on recursive self-improvement.

The AI Daily Brief helps you understand the most important news and discussions in AI.
Subscribe to the podcast version of The AI Daily Brief wherever you listen: https://pod.link/1680633614
Get it ad free at http://patreon.com/aidailybrief
Learn more about the show https://aidailybrief.ai/

Read the whole story
alvinashcraft
12 minutes ago
reply
Pennsylvania, USA
Share this story
Delete

How to Build a Secure Password Generator with Python

1 Share

A while ago I decided to build a password generator just to practice some Python. I fired up the editor, put together a script with the random module, and it worked great: if you give it a length, it spits out a string of characters.

Later, I found out that using random for anything that needs to be secure is a really bad idea. So, in this tutorial I’m going to show you why that module is unsuitable for security, and how to make a proper secure password generator with the secrets module instead.

So, this isn’t just another “here’s a password generator” tutorial. By the end, you'll know how to write a secure Python script, handle user input gracefully, and understand why standard random number generators aren't safe for passwords.

What We'll Cover:

How Most Beginners Write It and Mess it Up

This is what I (and pretty much every beginner) starts with:

import random
import string

chars = string.ascii_letters + string.digits
password = ''.join(random.choice(chars) for _ in range(12))
print(password)

It looks and runs fine. The passwords even look ok. The problem is that random is a pseudo-random number generator. It’s driven by a mathematical formula and a seed. If someone knows (or can guess) the seed, or sees enough outputs, the sequence becomes predictable.

For tasks like shuffling a playlist or rolling dice in a game, this is perfectly fine. But for passwords, it introduces a major security risk.

I used to think “random is random,” but apparently there’s a difference between “looks random” and “actually unpredictable.” I learned this lesson the hard way!

How to Use the Secrets Module for True Randomness

Python has a built-in module called secrets that’s made exactly for this kind of thing. Instead of relying on some predictable math formula, it pulls randomness straight from your operating system’s entropy source.

On Linux it grabs data from /dev/urandom, and on Windows it uses CryptGenRandom. Sounds a bit technical, but basically it just means it’s using the computer’s deepest, most secure source of randomness. That’s the standard way to handle passwords and security tokens in Python.

Here’s the basic secure version:

import secrets
import string

letters = string.ascii_letters
digits = string.digits
symbols = string.punctuation

all_chars = letters + digits + symbols

password = ''.join(secrets.choice(all_chars) for _ in range(16))
print(password)

The code is almost identical. The only real change is swapping random for secrets. That one swap is the entire point of this whole thing.

How to Make it Interactive with the User Input

Instead of hard-coding the length, let’s just ask the user for it. People might type letters or symbols by accident instead of a number, so we’ll throw in some error handling, so the script doesn’t crash.

import secrets
import string

print("===== SECURE PASSWORD GENERATOR =====")

while True:
    try:
        length = int(input("\nHow long should the password be? (minimum 8): "))
        if length >= 8:
            break
        print("The Password must be at least 8 characters")
    except ValueError:
        print("Invalid Input. Please enter a number.")

all_chars = string.ascii_letters + string.digits + string.punctuation
password = ''.join(secrets.choice(all_chars) for _ in range(length))

print(f"\nYour secure password is:{password}")

A few quick notes on what’s going on here:

  • The while True loop just keeps asking until it gets something usable.
  • The try/except block catches invalid inputs (like typing words instead of a number) so the script doesn't crash.
  • I set a minimum length of 8 characters because shorter passwords are easily compromised.

Save it as password_gen.py, run it with the python password_gen.py command, and you’re done. Try typing letters or a number under 8 to see if the error handling actually works. It’s oddly satisfying.

===== SECURE PASSWORD GENERATOR =====

How long should the password be? (minimum 8): 16

Here you go: k#P9$m!vQ2x@L8wE

What I Learned About Secure Code

One thing that still catches people is assuming that if the code runs and produces something that looks like a strong password, it must be fine. The first version I wrote ran perfectly and was still the wrong tool for the job. secrets is the one you want when the output needs to be hard to guess.

If you want to take it a bit further, you can force the password to include at least one number and one symbol, so it never comes out as pure letters. Or you can wrap it in a tiny GUI if you’re into that. I usually just keep the terminal version because it’s fast and I don’t have to think about it.

In summary, the main takeaway is to avoid the random module when building anything security-related. By switching to secrets and adding basic error handling for user input, you can create a script that is both secure and reliable. Now you have a tool you can actually trust to generate strong passwords.



Read the whole story
alvinashcraft
12 minutes ago
reply
Pennsylvania, USA
Share this story
Delete

EF Core Multiple Result Sets with Stored Procedures

1 Share

Back in 2015 I wrote about returning multiple result sets from a stored procedure with Entity Framework 6. People still land on that post, and the code in it doesn’t compile against anything modern. This is the Entity Framework Core 10 version.

The reason to do this hasn’t changed. A stored procedure that returns several result sets pipelines them over one connection in one round trip. If a page needs cats and dogs, one trip beats two. It’s not something I reach for often, but when I do, I want it to work without fighting the framework.

Everything here was run against EF Core 10.0.15 and SQL Server 2022.

What Changed Since EF6?

The EF6 trick relied on this:

((IObjectContextAdapter) db).ObjectContext.Translate<Cat>(reader)

ObjectContext, IObjectContextAdapter, and Translate<T> don’t exist in EF Core. There’s no built-in replacement. Database.SqlQuery<T> (added in EF Core 7) can map unmapped types, but it only reads the first result set.

What does still exist is plain ADO.NET, and EF Core gives you the connection through Database.GetDbConnection().

The Data

Same two tables as the original, now with a couple of extra columns. Run this against SQL Server. I use a container locally.

CREATE TABLE [dbo].[Cats](
[Id] [int] IDENTITY(1,1) NOT NULL,
[Name] [nvarchar](50) NULL,
[Lives] [int] NOT NULL
)
CREATE TABLE [dbo].[Dogs](
[Id] [int] IDENTITY(1,1) NOT NULL,
[Name] [nvarchar](50) NULL,
[Breed] [nvarchar](50) NULL
)
INSERT INTO [dbo].[Cats] ([Name], [Lives]) VALUES ('Whiskers', 9), ('Tom', 7)
INSERT INTO [dbo].[Dogs] ([Name], [Breed]) VALUES ('Rex', 'Lab'), ('Fido', 'Pug')
GO
CREATE OR ALTER PROCEDURE [dbo].[Pets]
AS
BEGIN
SET NOCOUNT ON;
SELECT Id, Name, Lives FROM Cats;
SELECT Id, Name, Breed FROM Dogs;
END

And the types we want back. These don’t need to be in your DbContext.

public record CatDto(int Id, string Name, int Lives);
public record DogDto(int Id, string Name, string Breed);

The Gotcha: SqlQueryRaw Returns Only the First Result Set

The obvious EF Core move is SqlQueryRaw:

var cats = await db.Database
.SqlQueryRaw<CatDto>("EXEC dbo.Pets")
.ToListAsync();

It works. You get two cats and no error. You also silently lose the dogs. EF Core only ever sees the first result set, and there’s no API to advance to the next one.

Ask for the other type and it fails:

var dogs = await db.Database
.SqlQueryRaw<DogDto>("EXEC dbo.Pets")
.ToListAsync();
// InvalidOperationException: The required column 'Breed' was not present
// in the results of a 'FromSql' operation.

That’s because it’s matching DogDto against the cat columns. One more trap: use SqlQueryRaw, not the interpolated SqlQuery($"..."), for the statement text. If you interpolate the whole statement, EF Core turns it into a parameter and SQL Server answers with Could not find stored procedure 'EXEC dbo.Pets'.

So SqlQuery is out for multiple result sets. Drop down a level.

The Manual Way: GetDbConnection and NextResultAsync

var conn = db.Database.GetDbConnection();
await db.Database.OpenConnectionAsync();
await using var cmd = conn.CreateCommand();
cmd.CommandText = "dbo.Pets";
cmd.CommandType = CommandType.StoredProcedure;
await using var reader = await cmd.ExecuteReaderAsync();
var cats = new List<CatDto>();
while (await reader.ReadAsync())
{
cats.Add(new CatDto(
reader.GetInt32(0),
reader.GetString(1),
reader.GetInt32(2)));
}
await reader.NextResultAsync();
var dogs = new List<DogDto>();
while (await reader.ReadAsync())
{
dogs.Add(new DogDto(
reader.GetInt32(0),
reader.GetString(1),
reader.GetString(2)));
}

I call OpenConnectionAsync() on the Database facade so EF Core owns the connection lifetime. It’s small and has no dependencies. The cost is that you map columns by hand, and anything you read this way is not tracked by the change tracker.

The Reusable Way: A Fluent MultipleResults Extension

The 2015 post had a MultipleResults().With<Cat>().With<Dog>() wrapper that returned untyped IEnumerables you had to Cast. Here’s the modern version: async, strongly typed, and it returns a tuple.

using System.Data;
using System.Data.Common;
using System.Reflection;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Storage;
public static class MultipleResultsExtensions
{
public static MultiReader MultipleResults(
this DatabaseFacade facade,
string sql,
CommandType type = CommandType.Text,
params DbParameter[] parameters)
=> new(facade, sql, type, parameters);
public static T MapByName<T>(this DbDataReader r)
where T : new()
{
var o = new T();
var props = typeof(T).GetProperties(
BindingFlags.Public | BindingFlags.Instance);
foreach (var p in props)
{
int i;
try
{
i = r.GetOrdinal(p.Name);
}
catch (IndexOutOfRangeException)
{
continue;
}
if (!r.IsDBNull(i))
{
p.SetValue(
o,
Convert.ChangeType(
r.GetValue(i),
Nullable.GetUnderlyingType(p.PropertyType)
?? p.PropertyType));
}
}
return o;
}
}
public class MultiReader(
DatabaseFacade db,
string sql,
CommandType type,
DbParameter[] ps)
{
public MultiReader<T1> With<T1>(Func<DbDataReader, T1> m)
=> new(db, sql, type, ps, m);
public MultiReader<T1> With<T1>()
where T1 : new()
=> new(db, sql, type, ps, r => r.MapByName<T1>());
}
public class MultiReader<T1>(
DatabaseFacade db,
string sql,
CommandType type,
DbParameter[] ps,
Func<DbDataReader, T1> m1)
{
public MultiReader<T1, T2> With<T2>(Func<DbDataReader, T2> m)
=> new(db, sql, type, ps, m1, m);
public MultiReader<T1, T2> With<T2>()
where T2 : new()
=> new(db, sql, type, ps, m1, r => r.MapByName<T2>());
}
public class MultiReader<T1, T2>(
DatabaseFacade db,
string sql,
CommandType type,
DbParameter[] ps,
Func<DbDataReader, T1> m1,
Func<DbDataReader, T2> m2)
{
public async Task<(List<T1>, List<T2>)> ExecuteAsync(
CancellationToken ct = default)
{
var conn = db.GetDbConnection();
var wasClosed = conn.State != ConnectionState.Open;
if (wasClosed)
{
await db.OpenConnectionAsync(ct);
}
try
{
await using var cmd = conn.CreateCommand();
cmd.CommandText = sql;
cmd.CommandType = type;
var tx = db.CurrentTransaction?.GetDbTransaction();
if (tx != null)
{
cmd.Transaction = tx;
}
foreach (var p in ps)
{
cmd.Parameters.Add(p);
}
await using var r = await cmd.ExecuteReaderAsync(ct);
var a = new List<T1>();
while (await r.ReadAsync(ct))
{
a.Add(m1(r));
}
await r.NextResultAsync(ct);
var b = new List<T2>();
while (await r.ReadAsync(ct))
{
b.Add(m2(r));
}
return (a, b);
}
finally
{
if (wasClosed)
{
await db.CloseConnectionAsync();
}
}
}
}

It joins the ambient transaction, only opens and closes the connection if it was closed, and supports parameters and CommandType. Extending it to three or four result sets means adding another MultiReader<...> class, which is boring but mechanical.

Usage with explicit mappers, which is the fast, trimming-friendly option:

var (cats, dogs) = await db.Database
.MultipleResults("dbo.Pets", CommandType.StoredProcedure)
.With(r => new CatDto(r.GetInt32(0), r.GetString(1), r.GetInt32(2)))
.With(r => new DogDto(r.GetInt32(0), r.GetString(1), r.GetString(2)))
.ExecuteAsync();

Or the reflection-based convenience version, for classes with a parameterless constructor that match columns by name:

public class CatRow
{
public int Id { get; set; }
public string Name { get; set; } = "";
public int Lives { get; set; }
}
public class DogRow
{
public int Id { get; set; }
public string Name { get; set; } = "";
public string Breed { get; set; } = "";
}
var (cats, dogs) = await db.Database
.MultipleResults("dbo.Pets", CommandType.StoredProcedure)
.With<CatRow>()
.With<DogRow>()
.ExecuteAsync();

Both returned two cats and two dogs against SQL Server 2022.

The Alternative: Dapper QueryMultipleAsync

If you’d rather not own that code, Dapper already does this. Point it at the connection EF Core gives you:

using Dapper;
var conn = db.Database.GetDbConnection();
using var grid = await conn.QueryMultipleAsync(
"dbo.Pets",
commandType: CommandType.StoredProcedure);
var cats = grid.Read<CatRow>().ToList();
var dogs = grid.Read<DogRow>().ToList();

That’s the lowest-effort option, at the price of a dependency. If Dapper is already in your project, use it.

Do You Need MARS?

No. This one trips people up because of the name. I ran every example above with a connection string that had no MultipleActiveResultSets setting, and NextResult worked fine.

MARS (Multiple Active Result Sets) lets you have more than one concurrent command or open reader on a single connection, for example looping over one reader while issuing another query on the same connection. Reading several result sets from one command, one after the other, is a different thing and works without it.

Wrapping Up

EF Core dropped Translate<T>, and SqlQuery/SqlQueryRaw only gives you the first result set without telling you. Reach for GetDbConnection() and NextResultAsync() directly, wrap it in a helper if you do it often, or hand the connection to Dapper.

If you want the original, the EF6 version from 2015 is still up. For the older .NET Core take on the same idea, see Multiple Result Sets With .Net Core and SQL Server.


Written by Khalid Abuhakmeh. If this guide helped your workflow, feel free to buy me a coffee.

Read the whole story
alvinashcraft
13 minutes ago
reply
Pennsylvania, USA
Share this story
Delete
Next Page of Stories