.Net Core how to implement SQLAdapter ./ DataTable function

后端 未结 4 2098
没有蜡笔的小新
没有蜡笔的小新 2020-12-31 04:51

I have a simple .Net Framework routine which runs a query and returns a DataTable object. I need to port this to .Net Core, however I infer that SQLAdapter and DataTable ar

4条回答
  •  庸人自扰
    2020-12-31 05:26

    UPDATE: This answer corresponds to .NET Core 1.x (which was the latest at the time I wrote this). If you are using .NET Core 2.x (in beta as of July/2017), check Joe's answer.

    Original answer:

    Recommended read: Porting to .NET Core

    I quote:

    • System.Data. While the base layer is already part of .NET Core, i.e. the provider model and SQL client, some features are currently not available, such as schema support and DataTable/DataSet.

    You can use SqlDataReader but not SqlAdapter or DataTable.

    Start by adding System.Data.SqlClient NuGet Package.

    Then you can...

    var con = new SqlConnection("...");
    var cmd = con.CreateCommand();
    cmd.CommandText = "...";
    var reader = cmd.ExecuteReader();
    // populate your custom data structure
    

    Does IList> works for you?

    var results = new List>();
    
    while (reader.Read())
    {
        results.Add(Enumerable.Range(0, reader.FieldCount).ToDictionary(reader.GetName, reader.GetValue));
    }
    return results;
    

    So now you can read using results[0]["FirstName"].ToString()

    Unless you want to switch to Entity Framework Core, in that case this tutorial is handy.

提交回复
热议问题