Entity Framework Core on top of an AWS Aurora PostgreSQL cluster with a write/read node and a read only node

Viewed 4423

I have an API Gateway running .NET Core which proxies to AWS Lambda functions. Using Entity Framework Core, these Lambda functions communicate with an AWS Aurora PostgreSQL RDS Cluster. The cluster contains one read/write node and one read only node.

During setting up EF Core, I used database first to scaffold, which has worked fine. The scaffolding was done off the read/write instance of the cluster, and the read write instance is what is referenced in the context connection string in the resulting DatabaseContext class.

However, I have some read intensive API methods (and resulting Lambda functions) that I would like to point specifically to my read only node (which has sub-second replication from the read/write node managed automatically by AWS). I have no idea however, how to set this up in my EF Core implementation. I am a beginner with EF Core, so I've been really happy that I have it working with the one node. How do I set things up in my .NET Core application so I can specify some queries to go to the read only node? The read only node has exactly the same schema and objects.

If I try to do a database first scaffold using the db context scaffold via the EF Core CLI but point it to the read only node, will that work? Or fail miserably? Is there some kind of specific way I should be setting this up? Or should I avoid EF Core for the read only node, and just use something like Dapper or SqlKata to do the read only queries and maintain its own connections etc?

1 Answers

Assuming your Context is named DbContext extend it like that:

public class RwDbContext : DbContext {}
public class RoDbContext : DbContext {}

And then, in Startup.cs register this contexts and point them to different connection strings:

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<RwDbContext>(options => options.UseNpgsql(Configuration.GetConnectionString("RwDbContext")));
    services.AddDbContext<RoDbContext>(options => options.UseNpgsql(Configuration.GetConnectionString("RoDbContext")));
}

Also add the connection string to your appsettings.json:

{
  "ConnectionStrings": {
    "RwDbContext": "Host=rwdb;...",
    "RoDbContext": "Host=rodb;..."
  }
}

Now you can use the RoDbContext for reading and RwDbContext for writing.

But when interacting with dotnet ef you have to use the --context <DBCONTEXT> option to point it to the R/W Context from now on.

Related