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));
when I update something with my writer db context, I get this 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.
DbContextand associating them to entities on the WriteDbContextthen the fact that Read isAsNoTrackingwon't be relevant to the problem, it will be how you are trying to pass references into the WriteDbContext.await readDbContext.EngineData.Where(or => or.Id == id).ToListAsync();and then in a different method, I am executing this line which is where I am getting the exception-context.EngineData.Update(outstandingRequest); await context.SaveChangesAsync();