Пример #1
0
        public IUnitOfWork GetUnitOfWork()
        {
            if (_UnitOfWork != null)
                throw new Exception("A unit of work is already in use");
            else
            {
                if(! KeepConnectionAlive)
                {
                    _Context = new WADbContext(DatabaseName);

                    if(_FirstRequest)
                    {
                        _Context.Database.Initialize(force: false);
                        _FirstRequest = false;
                    }
                }
                else
                {
                    if(_DbConnection == null)
                    {
                        string connectionString = null;

                        if(DisableSqlCe)
                        {
                            _DbConnection = new SqlConnection();

                            connectionString = @" Server=.\SQLEXPRESS; Database=" +
                                DatabaseName +
                                "; Trusted_Connection=true";
                        }
                        else
                        {
                            // using SqlCe
                            _DbConnection = new SqlCeConnection();
                            connectionString = "Data Source=" + DatabaseName;
                        }

                        // create a context and initialize the db on startup
                        if(_FirstRequest)
                        {
                            using (var tempContext = new WADbContext(connectionString))
                            {
                                tempContext.Database.Initialize(force: false);
                            }

                            _FirstRequest = false;
                        }

                        _DbConnection.ConnectionString = connectionString;
                        _DbConnection.Open();
                    }

                    _Context = new WADbContext(_DbConnection, false);
                }

                _UnitOfWork = new UnitOfWork(_Context);

                return _UnitOfWork;
            }
        }
Пример #2
0
        public virtual void ReturnUnitOfWork()
        {
            if( _UnitOfWork != null)
            {
                // if we do not own the connection, it should be already closed
                if (!KeepConnectionAlive)
                {
                    if (_DbConnection != null)
                        throw new Exception("Database is not null in connected state");
                }
                else if (_DbConnection == null || _DbConnection.State != System.Data.ConnectionState.Open)
                    throw new Exception("Database connection is not open in the connected state");

                // disposees dbcontext as well
                _UnitOfWork.Dispose();
                _UnitOfWork = null;
                _Context = null;
            }
        }