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





沒有留言:

張貼留言