Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class MongoDBManager
- {
- Mongo driver = new Mongo();
- MongoDB.Driver.Database currentDatabase;
- public MongoDBManager(string database)
- {
- driver = new Mongo();
- driver.Connect();
- currentDatabase = driver[database];
- }
- public T FindOne<T>(T specs) where T : IMongoPersistableObject
- {
- IMongoCollection c = GetCollection<T>();
- Document spec = ConvertSpecsToDocument(specs);
- Document result = c.FindOne(spec);
- if (result != null)
- return ConvertFromDocument<T>(result);
- return default(T);
- }
- public IEnumerable<T> Find<T>(T specs) where T : IMongoPersistableObject
- {
- IMongoCollection c = GetCollection<T>();
- Document specDocument = ConvertSpecsToDocument(specs);
- ICursor results = c.Find(specDocument);
- foreach (Document document in results.Documents)
- {
- yield return ConvertFromDocument<T>(document);
- }
- }
- private T ConvertFromDocument<T>(Document result) where T : IMongoPersistableObject
- {
- T o = Activator.CreateInstance<T>();
- foreach (var field in typeof(T).GetFields())
- {
- object val;
- if ((val = result[field.Name]) != null)
- field.SetValue(o, val);
- }
- IMongoPersistableObject mpo = (IMongoPersistableObject)o;
- mpo.DatabaseId = (Oid)result["_id"];
- return o;
- }
- private Document ConvertToDocument<T>(T o)
- {
- Document doc = new Document();
- foreach (var field in typeof(T).GetFields())
- {
- doc.Add(field.Name, field.GetValue(o));
- }
- return doc;
- }
- private Document ConvertSpecsToDocument<T>(T specs)
- {
- Document doc = new Document();
- foreach (var field in typeof(T).GetFields())
- {
- object value = field.GetValue(specs);
- if (value != null)
- doc.Add(field.Name, value.ToString());
- }
- return doc;
- }
- private IMongoCollection GetCollection<T>()
- {
- return currentDatabase.GetCollection(typeof(T).FullName);
- }
- public T Persist<T>(T o) where T : IMongoPersistableObject
- {
- IMongoPersistableObject mpo = (IMongoPersistableObject)o;
- if (mpo.DatabaseId == null)
- {
- return Insert<T>(o);
- }
- else
- {
- return Update<T>(o);
- }
- }
- private T Insert<T>(T o) where T : IMongoPersistableObject
- {
- IMongoCollection table = GetCollection<T>();
- table.Insert(ConvertToDocument(o));
- return o;
- }
- private T Update<T>(T o) where T : IMongoPersistableObject
- {
- IMongoCollection table = GetCollection<T>();
- Document d = ConvertToDocument<T>(o);
- IMongoPersistableObject mpo = (IMongoPersistableObject)o;
- d["_id"] = mpo.DatabaseId;
- table.Update(d);
- return o;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement