I have 2 database (AWS Aurora Postgres) instances – reader instance and writer instance. There are 2 different connection strings for the instances and I want to utilize both instances.
I want to use reader instance to run DQL commands and writer instance run other commands.
I have a class called DatabaseContext
which has the following code:
using Microsoft.EntityFrameworkCore;
namespace Com.Proj.Repository
{
public class DatabaseContext : DbContext
{
public DatabaseContext(DbContextOptions<DatabaseContext> options) : base(options)
{
}
public DbSet<Data> EngineData { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Data>(entity =>
{
entity.HasKey(k => k.Id);
entity.Property(t => t.Id).HasColumnName("id");
entity.Property(t => t.Data).HasColumnName("data");
entity.Property(t => t.Time).HasColumnName("time");
});
}
}
}
I created another file with same exact code but with a different class name ReadDatabaseContext
and in dependency injection, I did:
services.AddDbContext<ReadDatabaseContext>(options => options.UseNpgsql(readDbConnection, options => options.EnableRetryOnFailure(3, TimeSpan.FromSeconds(2), null))
.UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking));
but I get an error:
instance of entity type cannot be tracked because another instance with same key value is tracked
I added this code in my ReadDatabaseContext
:
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking);
}
I also added .AsNoTracking()
wherever I am using the ReadDatabaseContext
to read data.
But nothing worked.