非静态字段、方法或 属性 `Program.InsertLogData()` 需要对象引用

An Object reference is required for the non-static field, method, or property `Program.InsertLogData()`

实施建议的代码后,我收到一条错误消息:

An Object reference is required for the non-static field, method, or property Program.InsertLogData()

用于 await insertlogdata()

的 try 块

我是否可以删除 main 中的 static 一词并保留它 public 异步任务?

在给出建议后更新了代码:

命名空间 ElasticSearchConsoleApp { class 程序 { 私人只读 IElasticClient _elasticClient;

    public Program()
    {
        _elasticClient = new ElasticClient();
    }
    public static async Task Main(string[] args)
    {
        Console.Write("getting connection...");


        try
        {
            await InsertLogData();
        }
        catch(Exception ex)
        {
            Console.Write("Error: " + ex.Message);
        }

        Console.ReadLine();


    }

    public async Task<int> InsertLogData()
    {
        SqlConnection connection = null;
        SqlCommand command = null;
        int numrows = 0;

        try
        {
            var response = await _elasticClient.SearchAsync<Object>(s => s
                .Size(3000)
                .Index("customer-simulation-es-app-logs*")
                .Query(q => +q
                    .DateRange(dr => dr
                        .Field("@timestamp")
                            .GreaterThanOrEquals("2021-06-07T17:13:54.414-05:00")
                            .LessThanOrEquals(DateTime.Now))));

            connection = new SqlConnection("Data Source=.\SQLExpress;Database=ElasticSearchService;Trusted_Connection=True;");

            connection.Open();

            foreach (var item in response.Hits)
            {
                var id = item.Id;
                var sourceItem = item.Source;

                var json = _elasticClient.RequestResponseSerializer.SerializeToString(sourceItem);

                command = new SqlCommand("INSERT INTO EsLogs (ELKLogID, LogMessage, DateCreated) VALUES ('" + id + "','" + json + "', getdate())", connection);

                numrows = command.ExecuteNonQuery();
            }

            connection.Close();

        }
        catch (Exception ex)
        {
            Debug.WriteLine(ex.Message);
        }
        finally
        {
            command.Dispose();
            connection.Dispose();


        }
        return numrows;
    }

}

}

你必须修复弹性客户端。

private static readonly IElasticClient _elasticClient = new ElasticClient();

//  public Program()
//  {
//  }

在此之后您将遇到另一个错误。您必须通过放置来修复您的 foreach 循环 command.ExecuteNonQuery 循环内部


 connection.Open();
foreach (var item in response.Hits)
 {
 var id = item.Id;
  var sourceItem = item.Source;
 var json = _elasticClient.RequestResponseSerializer.SerializeToString(sourceItem);

 command = new SqlCommand("INSERT INTO EsLogs (ELKLogID, LogMessage, DateCreated) VALUES ('" + id + "','" + json + "', getdate())", connection);

 numrows = command.ExecuteNonQuery();
}

 connection.Close();

顺便说一下,您必须考虑为查询使用参数