有没有办法在不使用EF的情况下将MSSQL服务器连接到.NET CORE(2.2)API?

时间:2019-02-21 07:32:59

标签: c# .net api asp.net-core .net-core

我是.Net Core的新手,到目前为止,我正尝试从.Net Core API连接MSSQL Server中的现有数据库。

但是我发现的所有示例都是使用EF。

但是我想按如下方式从用户定义的类连接MSSQL服务器。

DataBaseConnection.cs

 public class DatabaseConnection 
    {
        private SqlDataAdapter sqlAdapter;
        private SqlConnection sqlConnection;
        SqlCommand sqlCommand = new SqlCommand();

        // Initialise Connection

        public DatabaseConnection()
        {
            sqlAdapter = new SqlDataAdapter();
            sqlConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);
        }

        // Open Database Connection if Closed or Broken

        private SqlConnection openConnection()
        {
            if (sqlConnection.State == ConnectionState.Closed || sqlConnection.State == ConnectionState.Broken)
            {
                sqlConnection.Open();
            }
            return sqlConnection;
        }
}

在构造函数中,我得到的错误为

enter image description here

appsettings.json

{
  "ConnectionStrings": {
    "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=HealthAPI;Trusted_Connection=True;MultipleActiveResultSets=true"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "AllowedHosts": "*"
}

是否有可能不使用EF与数据库建立连接?

2 个答案:

答案 0 :(得分:1)

我使用解决方法来做到这一点。下面是代码。

public abstract class BaseDataService
{
    private Database database = null;

    public BaseDataService()
    {
        DatabaseFactory.SetDatabaseProviderFactory(new DatabaseProviderFactory(new SystemConfigurationSource(false).GetSection), false);
        this.database = DatabaseFactory.CreateDatabase("_connection");
    }
    public Database SqlDatabase
    {
        get
        {
            return this.database;
        }

        set
        {
            this.database = value;
        }
    }
}

App.config文件

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="system.data" type="System.Data.Common.DbProviderFactoriesConfigurationHandler, Microsoft.Practices.EnterpriseLibrary.Data, Version=6.0.0.0, Culture=neutral, PublicKeyToken=null"/>
  </configSections>

  <connectionStrings>
    <add name="_connection" connectionString="Server=localhost;Database=DBNAME;Trusted_Connection=True;" providerName="System.Data.SqlClient"  />
  </connectionStrings>
</configuration>

用法

public class MyDataService : BaseDataService
{
    public IList<Test> ReadTest()
    {
        IList<Test> testList = new List<Test>();
        DbCommand selectCommand = null;

        selectCommand = SqlDatabase.GetStoredProcCommand("[dbo].[CSP_Test_SelectAll]");

        using (DataSet result = SqlDatabase.ExecuteDataSet(selectCommand))
        {
            if (result.Tables[0].Rows.Count > 0)
            {
                DataTable dataTable = result.Tables[0];
                feesList = dataTable.ConvertTo<Test>();
            }
        }

        return testList;
    }
}

需要的包裹

<PackageReference Include="EnterpriseLibrary.Data.NetCore" Version="6.0.1313" />

编辑:

我遍历了您的代码,问题是获取配置值

public DatabaseConnection(IConfiguration configuration)
{
      string connectionString = configuration.GetConnectionString("DefaultConnection");
      sqlAdapter = new SqlDataAdapter();
      sqlConnection = new SqlConnection(connectionString);
}

答案 1 :(得分:0)

像这样使用它

Configuration.GetSection("ConnectionStrings").DefaultConnection