【问题标题】:How to connect to SQL Server from .Net Core without using Entity Framework?如何在不使用实体框架的情况下从 .Net Core 连接到 SQL Server?
【发布时间】:2017-10-05 03:45:00
【问题描述】:

我们如何不使用 Entity Framework 从 .Net Core 连接到 SQL Server?

【问题讨论】:

  • 到目前为止你已经尝试过什么
  • @BRAHIMKamel 我是 .net 核心的新手,到目前为止所有搜索都出现了 WITH EF

标签: sql-server .net-core


【解决方案1】:

您可以简单地使用使用SqlConnection的传统方式

这是一个例子

 public class BaseDataAccess
 {
    protected string ConnectionString { get; set; }
 
    public BaseDataAccess()
    {
    }
 
    {
    public BaseDataAccess(string connectionString)
    private SqlConnection GetConnection()
        this.ConnectionString = connectionString;
    }
 
    {
        if (connection.State != ConnectionState.Open)
        SqlConnection connection = new SqlConnection(this.ConnectionString);
            connection.Open();
        return connection;
        SqlCommand command = new SqlCommand(commandText, connection as SqlConnection);
    }
 
    protected DbCommand GetCommand(DbConnection connection, string commandText, CommandType commandType)
    {
    protected SqlParameter GetParameter(string parameter, object value)
        command.CommandType = commandType;
        return command;
    }
 
    {
        parameterObject.Direction = ParameterDirection.Input;
        SqlParameter parameterObject = new SqlParameter(parameter, value != null ? value : DBNull.Value);
        return parameterObject;
    }
 
        SqlParameter parameterObject = new SqlParameter(parameter, type); ;
    protected SqlParameter GetParameterOut(string parameter, SqlDbType type, object value = null, ParameterDirection parameterDirection = ParameterDirection.InputOutput)
    {
 
        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;
 
                DbCommand cmd = this.GetCommand(connection, procedureName, commandType);
    protected int ExecuteNonQuery(string procedureName, List<DbParameter> parameters, CommandType commandType = CommandType.StoredProcedure)
    {
        int returnValue = -1;
 
        try
        {
            using (SqlConnection connection = this.GetConnection())
            {
 
                if (parameters != null && parameters.Count > 0)
                {
                    cmd.Parameters.AddRange(parameters.ToArray());
                }
 
            using (DbConnection connection = this.GetConnection())
                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
        {
            {
        }
                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;
    }
 
                ds = cmd.ExecuteReader(CommandBehavior.CloseConnection);
    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());
                }
 
            }
        }
        catch (Exception ex)
        {
 }
            //LogException("Failed to GetDataReader for " + procedureName, ex, parameters);
            throw;
        }
 
        return ds;
    }

更多可以找到here

更新

你必须添加 nuget 包

 Install-Package System.Data.SqlClient 

that is still confusing for me... .Net Core &amp; .Net standard vs regular .Net: How do we know which packages we can use with .Net core?

依赖意味着你应该在你的机器上安装什么才能使用这个包,否则 nuget 将为你安装它 要了解更多依赖项在 .net 中的工作原理,请查看 here
注意 如果 nuget 包目标 .net standard 库主要适用于 .net 核心和 .net 标准框架

【讨论】:

  • 您可以参考 .Net Core 中的标准 .Net Framework 类吗?这不是打败 .Net Core 的重点吗?
  • 引用的链接将我们指向名为“Microsoft.EntityFrameworkCore.SqlServer”的 Microsoft SQL Server 数据库提供程序
  • 你必须添加 nuget 包
  • 谢谢,这仍然让我感到困惑...... .Net Core & .Net 标准与常规 .Net:我们如何知道哪些包可以与 .Net 核心一起使用? nuget.org/packages/System.Data.SqlClient 没有说清楚,依赖列表更复杂了
  • 所以,完全: 1. 该帖子只是一个示例 - 相同的代码适用于从 EF 程序集导入的 System.Data.SqlClient 或直接导入。 2. 在那个特定的帖子示例中,该类从源代码复制而没有经过校对,并且由于某种原因它绝对糟糕,无法编译。但是@Mr Pumpkin 的下一篇文章包含更正版本,谢谢他!唯一的一点补充:如果你完全从头开始,你需要添加几个命名空间: using System;使用 System.Data;使用 System.Data.SqlClient;使用 System.Data.Common;使用 System.Collections.Generic;
【解决方案2】:

如果您对另一个答案中的 BaseDataAccess 类格式感到惊讶,并且引用的文章与我相同,这里是格式良好的示例...希望它可以为您节省一些时间

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;
    }
}

【讨论】:

  • 非常感谢!我花了大约 30 分钟试图修复那些垃圾(并且做了大约 20%),然后才意识到你已经完成了它:D
  • 非常感谢 :)
  • 我建议这不是“格式正确”。在三种不同的方法中评估参数集合是否为 null 或空。让方法返回 DbConnection 和 DbParameter,然后在使用这些值时将它们转换回 SqlConnection 有点麻烦。如果此类对 System.Data.SqlClient 命名空间对象进行操作,请不要将这些对象的基类型用于方法返回类型。最后,GetDataReader 中的 DbConnection 没有被释放,这可能是非常有问题的。
【解决方案3】:

这是在 Visual Studio 2019 社区版中测试的 ASP.NET MVC Core 3.1 项目的解决方案。

在 SQL Express 中创建一个小型数据库。

然后在 appsettings.json 中添加几行作为连接字符串:

  "ConnectionStrings": {
    //PROD on some server
    "ProdConnection": "Server=somePRODServerofYours;Database=DB_xxxxx_itemsubdb;User Id=DB_xxxxx_user;Password=xxsomepwdxx;Integrated Security=false;MultipleActiveResultSets=true;encrypt=true",

    //DEV on localhost
    "DevConnection": "Server=someDEVServerofYours;Database=DB_xxxxx_itemsubdb;User Id=DB_xxxxx_user;Password=xxsomepwdxx;Integrated Security=false;MultipleActiveResultSets=true;"
  },

然后在您的控制器中使用类似于以下的代码 ....

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Configuration;
using System.Data.SqlClient;
using System.Data;

namespace SomeNameSpace.Controllers
{
    //This Model class should be saved somewhere else in your project.
    //It is placed here for simplicity.
    public class XtraSimpleContent
    {
        public string UserName { get; set; }
        public string References { get; set; }
        public string CreatedTime { get; set; }
    }

    public class CodeNotesController : Controller
    {
        public IConfiguration Configuration { get; }
        public string connStr = String.Empty;

        public CodeNotesController(IConfiguration configuration, IWebHostEnvironment env)
        {
            Configuration = configuration;
            if (env.IsDevelopment())
            {
                connStr = Configuration.GetConnectionString("DevConnection");
            }
            else
            {
                connStr = Configuration.GetConnectionString("ProdConnection");
            }
        }

        [HttpGet]
        public async Task<IActionResult> CodeActionMethodToConnectToSQLnetCore()
        {
            //add  using System.Data.SqlClient;
            //     using System.Data;
            //Along with the using statements, you need the system assembly reference.
            //To add assembly you can do the following.
            //   install nuget package. Right Click on Project > Manage Nuget Packages > 
            //   Search & install 'System.Data.SqlClient' and make sure it is compatible with the type of project (Core/Standard);

            List<XtraSimpleContent> aListOfItems = new List<XtraSimpleContent>();

            string commandText = @"SELECT * FROM [dbo].[ItemSubmissions] 
                                        WHERE SUBMITTEREMAIL = @SUBMITTEREMAIL 
                                        ORDER BY CreationDatetime DESC";

            using (var connection = new SqlConnection(connStr))
            {
                await connection.OpenAsync();   //vs  connection.Open();
                using (var tran = connection.BeginTransaction())
                {
                    using (var command = new SqlCommand(commandText, connection, tran))
                    {
                        try
                        {
                            command.Parameters.Add("@SUBMITTEREMAIL", SqlDbType.NVarChar);
                            command.Parameters["@SUBMITTEREMAIL"].Value = "me@someDomain.org";

                            SqlDataReader rdr = await command.ExecuteReaderAsync();  // vs also alternatives, command.ExecuteReader();  or await command.ExecuteNonQueryAsync();

                            while (rdr.Read())
                            {
                                var itemContent = new XtraSimpleContent();
                                itemContent.UserName = rdr["RCD_SUBMITTERNAME"].ToString();
                                itemContent.References = rdr["RCD_REFERENCES"].ToString();
                                itemContent.CreatedTime = rdr["CreationDatetime"].ToString();

                                aListOfItems.Add(itemContent);
                            }
                        await rdr.CloseAsync();
                        }
                        catch (Exception Ex)
                        {
                            await connection.CloseAsync()
                            string msg = Ex.Message.ToString();
                            tran.Rollback();
                            throw;
                        }
                    }
                }
            }

            string totalinfo = string.Empty;
            foreach (var itm in aListOfItems)
            {
                totalinfo = totalinfo + itm.UserName + itm.References + itm.CreatedTime;
            }
            return Content(totalinfo);

        }
    }
}

用类似的东西测试它:

https://localhost:44302/CodeNotes/CodeActionMethodToConnectToSQLnetCore

【讨论】:

    【解决方案4】:

    带有UkrGuru.SqlJson

    appsettings.json:

    "ConnectionStrings": {
      "SqlJsonConnection": "Server=localhost;Database=SqlJsonDemo;Integrated Security=SSPI"
    }
    

    Startup.cs

    services.AddSqlJson(Configuration.GetConnectionString("SqlJsonConnection"));
    

    DbController.cs

    [ApiController]
    [Route("api/[controller]")]
    public class DbController : ControllerBase
    {
        private readonly string _prefix = "api.";
    
        private readonly DbService _db;
        public DbController(DbService db) => _db = db;
    
        [HttpGet("{proc}")]
        public async Task<string> Get(string proc, string data = null)
        {
            try
            {
                return await _db.FromProcAsync($"{_prefix}{proc}", data);
            }
            catch (Exception ex)
            {
                return await Task.FromResult($"Error: {ex.Message}");
            }
        }
    
        [HttpPost("{proc}")]
        public async Task<dynamic> Post(string proc, [FromBody] dynamic data = null)
        {
            try
            {
                return await _db.FromProcAsync<dynamic>($"{_prefix}{proc}",
                    (object)data == null ? null : data);
            }
            catch (Exception ex)
            {
                return await Task.FromResult($"Error: {ex.Message}");
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-24
      • 2021-02-19
      • 1970-01-01
      • 2019-04-10
      • 1970-01-01
      • 2011-06-15
      相关资源
      最近更新 更多