efcore.pg: "A command is already in progress" - connection pooling default configuration failing

Hi,

When using default pooling configuration on localhost DB, I have plenty of “a command is already in progress”, and sometimes, “connection already open” issues. I use traditional connection procedure services.AddEntityFrameworkNpgsql().AddDbContextPool<DBApiContext>(opt => opt.UseNpgsql(configuration.GetConnectionString("DBConnection"))); Connection String only activates Pooling=true. "DBConnection": "User ID=****;Password=****;Server=localhost;Port=5432;Database=*****;Pooling=true;", I used postgresql v9.5 and v10. .NETCore and PostgreSQL are hosted on the same machine. It sounds like the Pooling has not started ?

By the way, the connection to the DB is very easy:

var userQuery = this._db.PlaPlayer.Where(p => p.Nickname==credent.username);
if( userQuery.Count() != 1 ) 

Is there any way to track the Pooling activity? Or to enable it ? The model is easy too:

	public partial class DBApiContext : DbContext
	{
		public virtual DbSet<PlaPlayer> PlaPlayer { get; set; }

		public DBApiContext(DbContextOptions<DBApiContext> options)
			: base(options)
		{ }

		protected override void OnModelCreating(ModelBuilder modelBuilder)
		{
			modelBuilder.Entity<PlaPlayer>(entity =>
			{
				entity.ToTable("pla_player");

				entity.Property(e => e.Id)
					.HasColumnName("id");

				entity.HasIndex(e => e.Nickname)
					.HasName("nickname_unique")
					.IsUnique();

				entity.Property(e => e.Nickname)
					.IsRequired()
					.HasColumnName("nickname");
			});
		}
	}

About this issue

  • Original URL
  • State: closed
  • Created 6 years ago
  • Comments: 18 (8 by maintainers)

Most upvoted comments

A bit off topic but this was the #1 search result when googling “A command is already in progress.” This can also happen if you don’t dispose the reader before executing another command against the same connection.

The error “command already in progress” indicates that the same connection is being used concurrently. In EF Core this would generally mean that you’re trying to use the same DbContext instance twice at the same time. It seems from your code sample that you’re keeping a reference to the same DbContext instance (this._db) - this could be the source of your problem.

In general, DbContext instances are light and should be created every time you need to access the database - you should not in general be caching them in your code (although see EF Core 2.0’s new pooled contexts). Carefully look at what your code is doing and when each instance is used, to understand whether the same instance is accidentally used concurrently. If you can’t figure it out try to post a minimal code sample which reproduces the issue.

I had a similar problem and then I have added my context as transient my problem has been fixed. I just want to share my solution.

services.AddDbContext<DBContext>(<connectionstring>, ServiceLifetime.Transient);

this worked for me.