什么是DbContext在ADO.NET中做什么

时间:2017-03-04 10:00:05

标签: c# asp.net-mvc entity-framework asp.net-mvc-4 model-view-controller

我有代码连接到数据库并执行CRUD操作

请参阅以下代码:

我们在代码中使用了“DbContext”。 它是通用的,可以用于各种数据库,还是用于SQLServer,它的目的/任务是什么?

我认为DBContext仅用于实体框架

public class UserRepository : Repository<User>
{
    private DbContext _context;
    public UserRepository(DbContext context)
        : base(context)
    {
        _context = context;
    }


    public IList<User> GetUsers()
    {
        using (var command = _context.CreateCommand())
        {
            command.CommandText = "exec [dbo].[uspGetUsers]";

            return this.ToList(command).ToList();
        }
    }

    public User CreateUser(User user)
    {
        using (var command = _context.CreateCommand())
        {
            command.CommandType = CommandType.StoredProcedure;
            command.CommandText = "uspSignUp";

            command.Parameters.Add(command.CreateParameter("@pFirstName", user.FirstName));
            command.Parameters.Add(command.CreateParameter("@pLastName", user.LastName));
            command.Parameters.Add(command.CreateParameter("@pUserName", user.UserName));
            command.Parameters.Add(command.CreateParameter("@pPassword", user.Password));
            command.Parameters.Add(command.CreateParameter("@pEmail", user.Email));

            return this.ToList(command).FirstOrDefault();


        }

    }


    public User LoginUser(string id, string password)
    {
        using (var command = _context.CreateCommand())
        {
            command.CommandType = CommandType.StoredProcedure;
            command.CommandText = "uspSignIn";

            command.Parameters.Add(command.CreateParameter("@pId", id));
            command.Parameters.Add(command.CreateParameter("@pPassword", password));

            return this.ToList(command).FirstOrDefault();
        }
    }


    public User GetUserByUsernameOrEmail(string username, string email)
    {
        using (var command = _context.CreateCommand())
        {
            command.CommandType = CommandType.StoredProcedure;
            command.CommandText = "uspGetUserByUsernameOrEmail";

            command.Parameters.Add(command.CreateParameter("@pUsername", username));
            command.Parameters.Add(command.CreateParameter("@pEmail", email));

            return this.ToList(command).FirstOrDefault();
        }
    }


}

这是DbContext类:

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace DataAccessLayer
{
    public class DbContext
    {


        private readonly IDbConnection _connection;
        private readonly IConnectionFactory _connectionFactory;
        private readonly ReaderWriterLockSlim _rwLock = new ReaderWriterLockSlim();
        private readonly LinkedList<AdoNetUnitOfWork> _uows = new LinkedList<AdoNetUnitOfWork>();

        public DbContext(IConnectionFactory connectionFactory)
        {
            _connectionFactory = connectionFactory;
            _connection = _connectionFactory.Create();
        }

        public IUnitOfWork CreateUnitOfWork()
        {
            var transaction = _connection.BeginTransaction();
            var uow = new AdoNetUnitOfWork(transaction, RemoveTransaction, RemoveTransaction);

            _rwLock.EnterWriteLock();
            _uows.AddLast(uow);
            _rwLock.ExitWriteLock();

            return uow;
        }

        public IDbCommand CreateCommand()
        {
            var cmd = _connection.CreateCommand();

            _rwLock.EnterReadLock();
            if (_uows.Count > 0)
                cmd.Transaction = _uows.First.Value.Transaction;
            _rwLock.ExitReadLock();

            return cmd;
        }

        private void RemoveTransaction(AdoNetUnitOfWork obj)
        {
            _rwLock.EnterWriteLock();
            _uows.Remove(obj);
            _rwLock.ExitWriteLock();
        }

        public void Dispose()
        {
            _connection.Dispose();
        }
    }
}

2 个答案:

答案 0 :(得分:1)

您可以将EntityFramework用于execute raw SQL,但示例中的DbContext似乎不是来自EntityFramework的那个。它可以是项目中的其他库或自定义实现。您应该能够通过检查using导入或导航到DbContext定义来说明这一点。

答案 1 :(得分:0)

  

我认为DBContext仅用于实体框架

是的,DBContext是一个EntityFramework类,它结合了工作单元和存储库模式。

但是,您似乎已经使用ado.net创建了一个自定义DBContext。不过,我不会真正将其称为DBContext。由于通常DBContext遵循ObjectContext概念,即引用上下文对象(即在上下文中)。这个特定的自定义类更像是DbCommand工厂。

  

它是通用的,可以与各种数据库一起使用吗?还是为SQLServer设计的?[...]?

这不是特定于SQL Server的。因此,它可以与其他数据库一起使用,例如Oracle数据库,Microsoft SQL Server,MySQL,PostgreSQL,SQLite等。但是,这将取决于每个数据库的正确配置和正确的查询用法。例如,对于所有数据库,参数并不总是以@为前缀。但是,这个特殊的DBContext将这个问题传递给了调用它的类,并避免了处理它,正如我们在UserRepository中使用该类所看到的那样。

  

...及其目的/任务是什么?

您向我们展示的DBContext的目的是使用工厂获得连接,实例化并返回带有可选事务的DBCommand。并且,然后,存储库基类函数ToList似乎负责执行Command并映射对象User。

这似乎是尝试使用ado.net创建存储库模式。而且,由于不知道您的应用程序的历史,因此我只能假设已做出避免使用Entity Framework的决定。我已经看到了许多不同的方法。并且,很多人会争论正确的实施。但是,我认为这超出了此特定问题的范围。