2014年9月16日 星期二

Mongo DB repository for CRUD (2)

Mongo DB repository for CRUD (2)

A mongo worker for inheritance

public abstract class MongoWorker<T> : IDisposable
    {
        protected MongoServer _server = null;
        protected MongoClient _client = null;
        protected MongoDatabase _database = null;
        protected MongoCollection _collection = null;


        public MongoWorker(MongoConnTestPool mongoConnection, String collectionName)
        {
            if (mongoConnection == null || String.IsNullOrEmpty(collectionName))
            {
                throw new Exception("Mongo connect string and collection name must be provided!");
            }
            this._client = new MongoClient(mongoConnection.GetConnectionString());
            this._server = this._client.GetServer();
            this._database = _server.GetDatabase(collectionName);
            this._collection = _database.GetCollection<T>(collectionName);
            this._server.Connect();
        }

        public abstract IQueryable<T> Get();

        public abstract void Insert(T doc);

        public abstract void Delete(T doc);

        public abstract int Update(T doc);

        public virtual void Dispose()
        {
            try
            {
                if (this._server.State.Equals(MongoServerState.Connecting) ||
                    this._server.State.Equals(MongoServerState.Connected))
                {
                    this._server.Disconnect();
                }

                if(this._server!=null)
                {
                    this._server = null;
                }
                if (this._client != null)
                {
                    this._client = null;
                }
                if (this._database != null)
                {
                    this._database = null;
                }
                if (this._collection != null)
                {
                    this._collection = null;
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
    }






沒有留言:

張貼留言