顯示具有 MongoDB 標籤的文章。 顯示所有文章
顯示具有 MongoDB 標籤的文章。 顯示所有文章

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;
            }
        }
    }






2014年5月13日 星期二

Mongo DB repository for CRUD (1)

Mongo DB repository for CRUD

2.  Define a Customer model

using MongoDB.Bson.Serialization.Attributes;
public
class Customer
{
 [BsonId]
public string Id { get; set; }
public string Name { get; set; }
public string Phone { get; set; }
public string Email { get; set; }
public DateTime LastModified { get; set; }
}

3.  interface

public interface ICustomerRepository
{
IEnumerable<Customer> GetAll();
Customer Get(string id);
Customer Add(Customer item);
bool Delete(string id);
bool Update(string id, Customer item);
}

4.  implement the CRUD methods in CustomerRepository : ICustomerRepository

Constructor and private object :
Note that the official Mongo suggest to use
MongoClient to build the connection , instead of using
MongoServer _server = MongoServer.Create(…);

Private MongoServer _server = null;
private MongoDatabase _database = null;
private MongoCollection _customers = null;

public CustomerRepository(string connection)
{
if (string.IsNullOrEmpty(connection))
{
connection = "mongodb://localhost:27017"; //Mongo's default port is 27017
}
MongoClient client = new MongoClient(connection);
this._server = client.GetServer();
this._database = _server.GetDatabase("Customers");
this._customers = _database.GetCollection<Customer>("Customers");
this._server.Connect();
}


Get all documents from "Customers" collection :
public IEnumerable<Customer> GetAll()
{
return _Customers.FindAllAs<Customer>();
}


Get a document with certain id
public Customer Get(string id)
{
IMongoQuery query = MongoDB.Driver.Builders.Query<Customer>.EQ(e =>e.Id, id);
return this._customers.FindAs<Customer>(query).FirstOrDefault();
}


Insert a document
public Customer Add(Customer item)
{
item.Id = MongoDB.Bson.ObjectId.GenerateNewId().ToString();
item.LastModified = DateTime.Now;
this._customers.Insert(item);
return item;
}


Delete a document with id
public bool Delete(string id)
{
IMongoQuery query = MongoDB.Driver.Builders.Query<Customer>.EQ(e => e.Id, id);
var result = _customers.Remove(query);
return result.DocumentsAffected == 1;
}


Update a document

public bool Update(string id, Customer item)
{
IMongoQuery query = MongoDB.Driver.Builders.Query<Customer>.EQ(e => e.Id, id);           
item.LastModified = DateTime.UtcNow;
IMongoUpdate update = MongoDB.Driver.Builders.Update
                .Set("Email", item.Email)
                .Set("LastModified", DateTime.Now)
                .Set("Name", item.Name)
                .Set("Phone", item.Phone);
var result = _customers.Update(query, update);
return result.UpdatedExisting;
}


5.  AP layer (Web API)
Just use the methods in Web API.


6.  Test with Fiddler

Create





Get a document


Update

Delete


Note that you can use OData in Web API with Mongo as well.
ex. http://localhost:6691/api/customer?$orderby=Phone

7.  Reference