I have this code:
Program.cs
using System;
using System.Collections.Generic;
namespace sql
{
public class Program
{
public static void Main(string[] args)
{
var result = new List<SampleItem>();
result = Inventory.QueryStock();
foreach (var item in result)
{
Console.WriteLine("{0}", item.ItemCode);
}
}
}
}
sql.cs
using System;
using System.Data;
using System.Data.SqlClient;
using System.Threading.Tasks;
using System.Collections.Generic;
namespace sql
{
public class Inventory
{
public static async Task<List<SampleItem>> QueryStock()
{
if (Environment.GetEnvironmentVariable("SQL_CONNECTION_STRING") == null)
Environment.SetEnvironmentVariable("SQL_CONNECTION_STRING","Data Source=myServer;Initial Catalog=myDataBase;user id=sa;password=sql@123");
else
Console.WriteLine("sql connection already registered: ");
var connectionString = Environment.GetEnvironmentVariable("SQL_CONNECTION_STRING");
var sql = @"
SELECT
T0.ItemCode, T0.WhsCode, T0.OnHand,
T1.AvgPrice, T0.OnHand * T1.AvgPrice as [Value]
FROM
OITW T0
INNER JOIN
OITM T1 on T0.ItemCode = T1.ItemCode
WHERE
T0.itemcode LIKE 'RM%' AND T0.WhsCode ='RM' AND T0.onHand > 0";
var items = new List<SampleItem>();
using (var cnx = new SqlConnection(connectionString))
{
using (var cmd = new SqlCommand(sql, cnx))
{
await cnx.OpenAsync();
using (var reader = await cmd.ExecuteReaderAsync(CommandBehavior.CloseConnection))
{
while (await reader.ReadAsync())
{
var item = new SampleItem
{
ItemCode = reader.GetString(0)
};
items.Add(item);
}
}
}
}
return items;
}
}
public class SampleItem
{
public string ItemCode { get; set; }
}
}
and added the required dependencies System.Data.SqlClient
to the JSON file to get:
project.json
{
"version": "1.0.0-*",
"buildOptions": {
"debugType": "portable",
"emitEntryPoint": true
},
"dependencies": {
"System.Data.SqlClient": "4.1.0"
},
"frameworks": {
"netcoreapp1.0": {
"dependencies": {
"Microsoft.NETCore.App": {
"type": "platform",
"version": "1.0.1"
}
},
"imports": "dnxcore50"
}
}
}
The issue I've is the returned async result from the QueryStock()
is not captured in the Main
function, due to the unexisting of await
and if I used await
then it ask for the Main
to be async
, and if I made it async
it tells the Entry point Main
can not be async
?
UPDATE
Considering the question had been blocked for answers, I just re-writing Rubbke comment that solved by issue, for easy eye catching:
result = Inventory.QueryStock().Result;
another solution I found that help as well is:
result = Inventory.QueryStock().GetAwaiter().GetResult();