.NET Core中的ADO.NET可能吗?

Mr_*_*Mac 50 asp.net asp.net-mvc

我想使用最新版本的ASP.NET Core,因为我想用它创建一组Web API.但是,我发现的教程主要关注实体框架.我无法使用它,因为我已经拥有"遗留"数据库,因此Code-First方法不是一种选择.

我的想法是使用ADO.NET连接到我的数据库,但我不知道是否System.Data.SqlClient在ASP.NET Core项目中可用.我已经发现,当我使用.NET Framework项目模板但是它仍然可以在.NET Core项目中使用时可用吗?

Rio*_*ams 22

现有的SqlConnection和其他相关的连接仍然存在于System.Data.SqlClient命名空间内,并且应该使用完整框架或.NET Core按预期工作.

您只需要添加适当的引用并使用语句来包含它,例如通过System.Data.SqlClient命名空间,如下面的project.json文件中所示:

在此输入图像描述

然后通过您习惯的语法调用它:

using(var connection = new SqlConnection("{your-connection-string}"))
{
      // Do work here
}
Run Code Online (Sandbox Code Playgroud)

因此,只要您有一个有效的连接字符串来连接到现有的旧数据库,您应该没问题.

关于ORM使用

我还发现有些人正在使用Dapper,一个Micro-ORM替代实体框架,显然更灵活.使用它代替ADO.NET有什么好处吗?

这些ORM(对象关系映射器)是方便且通常功能强大的工具,可以更轻松地将现有数据库数据映射到特定类和对象,这可以使它们更易于使用(而不是通过数据读取器迭代,解析每个行和手动构建每个对象).

就性能而言,它最终取决于您将对查询执行的操作.ADO.NET通常是最快的,因为它是与数据库的简单连接,但在某些情况下,Dapper实际上可以击败它.实体框架虽然非常有用,但通常落后于性能,仅仅因为它是如此大的ORM.

再次 - 它最终取决于你在做什么,但都是可行的选择.

  • “遗留数据库”是什么意思? (2认同)

Joe*_*aly 17

.NET Core 2.0具有DataSet,DataTable和SQlDataAdapter.请参阅https://blogs.msdn.microsoft.com/devfish/2017/05/15/exploring-datatable-and-sqldbadapter-in-asp-net-core-2-0/上的答案.

下面的代码工作正常

public static DataTable ExecuteDataTableSqlDA(SqlConnection conn, CommandType cmdType, string cmdText, SqlParameter[] cmdParms)
 {
 System.Data.DataTable dt = new DataTable();
 System.Data.SqlClient.SqlDataAdapter da = new SqlDataAdapter(cmdText, conn);
 da.Fill(dt);
 return dt;
 }
Run Code Online (Sandbox Code Playgroud)


Imr*_*ved 9

值得注意的是,.NET Core在2.0版之前没有DataSet,DataTable和相关对象.但在2.0之前,它具有连接,命令,参数,DataReader和其他相关对象的所有核心功能.

您可以使用以下调用来简化通过SQL Server数据库提供程序与SQL Server的连接.

public class BaseDataAccess
{
    protected string ConnectionString { get; set; }

    public BaseDataAccess()
    {
    }

    public BaseDataAccess(string connectionString)
    {
        this.ConnectionString = connectionString;
    }

    private SqlConnection GetConnection()
    {
        SqlConnection connection = new SqlConnection(this.ConnectionString);
        if (connection.State != ConnectionState.Open)
            connection.Open();
        return connection;
    }

    protected DbCommand GetCommand(DbConnection connection, string commandText, CommandType commandType)
    {
        SqlCommand command = new SqlCommand(commandText, connection as SqlConnection);
        command.CommandType = commandType;
        return command;
    }

    protected SqlParameter GetParameter(string parameter, object value)
    {
        SqlParameter parameterObject = new SqlParameter(parameter, value != null ? value : DBNull.Value);
        parameterObject.Direction = ParameterDirection.Input;
        return parameterObject;
    }

    protected SqlParameter GetParameterOut(string parameter, SqlDbType type, object value = null, ParameterDirection parameterDirection = ParameterDirection.InputOutput)
    {
        SqlParameter parameterObject = new SqlParameter(parameter, type); ;

        if (type == SqlDbType.NVarChar || type == SqlDbType.VarChar || type == SqlDbType.NText || type == SqlDbType.Text)
        {
            parameterObject.Size = -1;
        }

        parameterObject.Direction = parameterDirection;

        if (value != null)
        {
            parameterObject.Value = value;
        }
        else
        {
            parameterObject.Value = DBNull.Value;
        }

        return parameterObject;
    }

    protected int ExecuteNonQuery(string procedureName, List<DbParameter> parameters, CommandType commandType = CommandType.StoredProcedure)
    {
        int returnValue = -1;

        try
        {
            using (SqlConnection connection = this.GetConnection())
            {
                DbCommand cmd = this.GetCommand(connection, procedureName, commandType);

                if (parameters != null && parameters.Count > 0)
                {
                    cmd.Parameters.AddRange(parameters.ToArray());
                }

                returnValue = cmd.ExecuteNonQuery();
            }
        }
        catch (Exception ex)
        {
            //LogException("Failed to ExecuteNonQuery for " + procedureName, ex, parameters);
            throw;
        }

        return returnValue;
    }

    protected object ExecuteScalar(string procedureName, List<SqlParameter> parameters)
    {
        object returnValue = null;

        try
        {
            using (DbConnection connection = this.GetConnection())
            {
                DbCommand cmd = this.GetCommand(connection, procedureName, CommandType.StoredProcedure);

                if (parameters != null && parameters.Count > 0)
                {
                    cmd.Parameters.AddRange(parameters.ToArray());
                }

                returnValue = cmd.ExecuteScalar();
            }
        }
        catch (Exception ex)
        {
            //LogException("Failed to ExecuteScalar for " + procedureName, ex, parameters);
            throw;
        }

        return returnValue;
    }

    protected DbDataReader GetDataReader(string procedureName, List<DbParameter> parameters, CommandType commandType = CommandType.StoredProcedure)
    {
        DbDataReader ds;

        try
        {
            DbConnection connection = this.GetConnection();
            {
                DbCommand cmd = this.GetCommand(connection, procedureName, commandType);
                if (parameters != null && parameters.Count > 0)
                {
                    cmd.Parameters.AddRange(parameters.ToArray());
                }

                ds = cmd.ExecuteReader(CommandBehavior.CloseConnection);
            }
        }
        catch (Exception ex)
        {
            //LogException("Failed to GetDataReader for " + procedureName, ex, parameters);
            throw;
        }

        return ds;
    }
 }
Run Code Online (Sandbox Code Playgroud)

有关更多详细信息和示例,请参阅以下文章:http: //www.ijz.today/2016/09/net-core-10-connecting-sql-server.html


ale*_*eha 7

正如Joe Healy 在DotNet Core 2.0 中的回答中所提到的,可以使用所有System.Data功能。

添加nuget:

  • Microsoft.Extensions.Configuration
  • Microsoft.Extensions.Configuration.Json-从json读取连接字符串
  • 系统数据通用
  • System.Data.SqlClient

config.json示例:

{
  "connectionString": "your-db-connection-settings"
}
Run Code Online (Sandbox Code Playgroud)

这是完整的控制台应用程序示例。

class Program
{
    static void Main(string[] args)
    {
        var configuration = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("config.json", false)
            .Build();

        var connectionString = configuration.GetSection("connectionString").Value;

        if(string.IsNullOrEmpty(connectionString))
            throw new ArgumentException("No connection string in config.json");

        using (var conn = new SqlConnection(connectionString))
        {
            var sql = "SELECT * FROM ExampleTable";
            using (var cmd = new SqlCommand(sql, conn))
            {
                using (var adapter = new SqlDataAdapter(cmd))
                {
                    var resultTable = new DataTable();
                    adapter.Fill(resultTable);
                }
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)