0

I have a C# Dotnet Core console Application. I am trying to connect NpgsqlConnection for PostgreSQL database (which is crate db). Im using this database for time series entry.I created the NpgsqlConnection in constructor of service.it's called every time . Is this a good way to call connection open in every time?. What is the alternative . In my project tables are not defined at the initial time. So DbContext is not useful. I think so?. Also some times below error is occurring.

{Npgsql.NpgsqlOperationInProgressException: A command is already in progress

My code is added below. How to create connection using NpgsqlConnection in time efficient way? Program.cs

static void Main(string[] args)
        {
            var builder = new ConfigurationBuilder()
   .SetBasePath(Directory.GetCurrentDirectory())
   .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
   .AddEnvironmentVariables();

           var configuration = builder.Build();    
           builder.RegisterType<TimeSeriesService>().As<ITimeSeriesService>();
           var npsqlconnectionString = "Host=172.18.0.2;Username=crate;SSL Mode=Prefer;Database=doc"; 
           builder.Register(c => new SensorDataRepository(npsqlconnectionString)).As<ISensorDataRepository>().SingleInstance();
           var DataProcessor = container.Resolve<ITimeSeriesService>();
           DataProcessor.ConsumeMsgs(brokeraddress, topic, groupid).GetAwaiter().GetResult();
           builder.RegisterInstance<IConfigurationRoot>(configuration);
           return builder.Build();


        }
      

Database Service.cs

public class SensorDataRepository : ISensorDataRepository
{
  public NpgsqlConnection conn { get; set; }
  public SensorDataRepository(string npsqlconnectionString)
  {
      
         NpgsqlDatabaseInfo.RegisterFactory(new CrateDbDatabaseInfoFactory());
         
  }

      public async Task InsertSensorData(SensorDataViewModel sensordata)
            {
               
            string sqlString = "Host=172.18.0.2;Username=crate;SSL Mode=Prefer;Database=doc";
            using (NpgsqlConnection sqlCon = new NpgsqlConnection(sqlString))
            {
                sqlCon.Open();
                string cmdString = $"INSERT INTO test1 (sensorid,deviceid,reading,timestamp) VALUES (@s,@d,@r,@t)";
                using (NpgsqlCommand sqlCmd = new NpgsqlCommand(cmdString, sqlCon))
                {
                    sqlCmd.Parameters.AddWithValue("s", sensordata.sensorid);
                    sqlCmd.Parameters.AddWithValue("d", sensordata.deviceid);
                    sqlCmd.Parameters.AddWithValue("r", sensordata.reading);
                    sqlCmd.Parameters.AddWithValue("t", sensordata.timestamp);

                  await sqlCmd.ExecuteNonQueryAsync();
                    
                } 
            }
            }

Edited: NpgsqlConnection added. Also console application is runs only once. And waiting for the next message.that means Constructor invoked only once

june alex
  • 244
  • 4
  • 17
  • 1
    "I created the NpgsqlConnection in constructor of service" not according to the code you've provided. – Ian Kemp Feb 22 '21 at 11:39
  • NpgsqlConnection added. – june alex Feb 22 '21 at 11:56
  • 1
    Using a global connection object is a *very* bad idea. Why are you writing such code at all? `So DbContext is not useful.` quite the opposite, in this case it would save you from critical bugs like connection leaks, SQL injection and conversion issues. *Don't* concatenate strings to create a query, don't use a global connection. Define the connection in a `using` block *inside* the `Insert` method. – Panagiotis Kanavos Feb 22 '21 at 12:01
  • 1
    Instead of trying to use patterns whether they help or not, get the simplest possible *correct* code to work *first*. Instead of string concatenation, use parameterized queries. You can use [Dapper](https://github.com/StackExchange/Dapper) to simplify the command execution code. – Panagiotis Kanavos Feb 22 '21 at 12:07
  • @PanagiotisKanavos i am very new to C# and PostgreSQL. Could you please give me an example ? – june alex Feb 22 '21 at 12:26
  • @PanagiotisKanavos . As per my understanding, If we are using DbContext ,we should know the Table name right ?. Tables are created at running time. That is the reason for i'm not using DbContext – june alex Feb 22 '21 at 13:07
  • @PanagiotisKanavos , changes made by your comment. could you please verify – june alex Feb 22 '21 at 14:31
  • @PanagiotisKanavos . is this the correct way ? – june alex Feb 22 '21 at 14:32

0 Answers0