如何使用DbContext进行原始SQL查询(每个请求一个连接)?

时间:2019-03-28 10:46:42

标签: c# entity-framework

我目前正在按照此说明说明如何在ef上使用原始sql进行查询。

https://docs.microsoft.com/en-us/ef/ef6/querying/raw-sql

是否可以通过这种方式在数据库上下文中执行原始sql读取查询,所以我们可以确保在请求处理期间仅使用一个数据库连接。

与此类似,但是使用DBContext代替od IDBConnection。

public class SqlConnectionFactory : ISqlConnectionFactory, IDisposable
    {
        private readonly string _connectionString;
        private IDbConnection _connection;

        public SqlConnectionFactory(string connectionString)
        {
            this._connectionString = connectionString;
        }

        public IDbConnection GetOpenConnection()
        {
            if (this._connection == null || this._connection.State != ConnectionState.Open)
            {
                this._connection = new SqlConnection(_connectionString);
                this._connection.Open();
            }

            return this._connection;
        }

        public void Dispose()
        {
            if (this._connection != null && this._connection.State == ConnectionState.Open)
            {
                this._connection.Dispose();
            }
        }
    }

0 个答案:

没有答案