Using standard defaults in C #

I have some code written in C #. I am trying to write some generic code that I can reuse. My actual code is more complex. However, the question with the code looks like this:

public async Task<T> ExecuteQueryAsync<T>(string sql)
{
  var results = default(T);
  using (var database = new SqlConnection("[ConnectionString]"))
  {
    database.Open();
    results = await database.QueryAsync<T>(sql);                        
  }
  return results;
}

      

When I build my project, I get a compile time error that reads:

Cannot implicitly convert type 'System.Collections.Generic.IEnumerable<T>' to 'T'. An explicit conversion exists (are you missing a cast?)

      

I am not entirely clear why I am getting this error. I intend to call it this way:

Adapter adapter = new Adapter();
var results = await adapter.ExecuteQueryAsync<IEnumerable<Customer>>("SELECT * FROM Customer");

      

In the above case T

, would n't it IEnumerable<T>

? If so, I don't understand why I am getting an error converting this type at compile time.

Thank!

+3


source to share


3 answers


Try something like this.



public async Task<IEnumerable<T>> ExecuteQueryAsync<T>(string sql)
{
  IEnumerable<T> results = Enumerable.Empty<T>();
  using (var database = new SqlConnection("[ConnectionString]"))
  {
    database.Open();
    results = await database.QueryAsync<T>(sql);                        
  }
  return results;
}

      

+5


source


In yours, ExecuteQueryAsync

you don't need a variable results

as you are always rewriting it. So your function could be like this



public async Task<IEnumerable<T>> ExecuteQueryAsync<T>(string sql)
{
    using (var database = new SqlConnection("[ConnectionString]"))
    {
        database.Open();
        return await database.QueryAsync<T>(sql);                        
    }
}

      

+3


source


There are already good answers here, but I wanted to make sure we have one that supports secure query parameterization. The source code forces you to write incredibly insecure code that will lead to your application being compromised. This avoids this:

public async Task<IEnumerable<T>> ExecuteQueryAsync<T>(string sql, dynamic Parameters = null)
{
  IEnumerable<T> results;
  using (var database = new SqlConnection("[ConnectionString]"))
  {
    database.Open();
    results = await database.QueryAsync<T>(sql, Parameters);                        
  }
  return results;
}

      

Then you can call it like this:

Adapter adapter = new Adapter();
var results = await adapter.ExecuteQueryAsync<IEnumerable<Customer>>(
        "SELECT * FROM Customer WHERE Sales >= @Sales", 
        new {Sales = 500.0m});

      

+1


source







All Articles