.NETMongodbHelper

 <add name="ConnectionString_mongoDB" connectionString="mongodb://sunbird:xxx@192.168.1.220:27017"/>
public class MongoDBHelper
    {

        private static readonly string connStr = ConfigurationManager.ConnectionStrings["ConnectionString_mongoDB"].ToString();
        public static readonly string dbName = ConfigurationManager.AppSettings["dbName"];

        private static IMongoDatabase db = null;

        private static readonly object lockHelper = new object();
        public MongoDBHelper()
        {
            if (db == null)
            {
                lock (lockHelper)
                {
                    if (db == null)
                    {

                        // MongoClientSettings mcs = new MongoClientSettings();
                        // mcs.SocketTimeout = TimeSpan.FromSeconds(15);
                        // mcs.MaxConnectionPoolSize = 10000;
                        //MongoServerAddress msa = new MongoServerAddress("192.168.1.220");
                        // //MongoServerAddress msa = new MongoServerAddress("182.254.242.57");
                        // mcs.Credentials = new List<MongoCredential>() { MongoCredential.CreateCredential(dbName, "sunbird", "Sunbird2017") };
                        // mcs.Server = msa;
                        // mcs.MaxConnectionIdleTime = TimeSpan.FromMilliseconds(60000);
                        // var client = new MongoClient(mcs);

                        var client = new MongoClient(connStr);
                        db = client.GetDatabase(dbName);

                    }
                }
            }
        }
        public T Insert<T>(T entity) where T : BaseEntity
        {

            var collection = db.GetCollection<T>(typeof(T).Name);
            var flag = ObjectId.GenerateNewId();
            entity.GetType().GetProperty("Id").SetValue(entity, flag);
            entity.State = "Y";
            entity.CreateTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            entity.UpdateTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            collection.InsertOne(entity);
            return QueryOne<T>(flag.ToString());
        }
        public async Task InsertAsync<T>(T entity) where T : BaseEntity
        {

            var collection = db.GetCollection<T>(typeof(T).Name);
            var flag = ObjectId.GenerateNewId();
            entity.GetType().GetProperty("Id").SetValue(entity, flag);
            entity.State = "Y";
            entity.CreateTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            entity.UpdateTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            await collection.InsertOneAsync(entity);
        }
        public void Modify<T>(string id, string field, string value) where T : BaseEntity
        {
            var collection = db.GetCollection<T>(typeof(T).Name);
            var filter = Builders<T>.Filter.Eq("Id", ObjectId.Parse(id));
            var updated = Builders<T>.Update.Set(field, value);
            UpdateResult result = collection.UpdateOneAsync(filter, updated).Result;
        }
        public void Update<T>(T entity) where T : BaseEntity
        {

            var collection = db.GetCollection<T>(typeof(T).Name);
            var old = collection.Find(e => e.Id.Equals(entity.Id)).ToList().FirstOrDefault();

            foreach (var prop in entity.GetType().GetProperties())
            {
                var newValue = prop.GetValue(entity);
                var oldValue = old.GetType().GetProperty(prop.Name).GetValue(old);
                if (newValue != null)
                {
                    if (oldValue == null || !newValue.ToString().Equals(oldValue.ToString()))
                    {
                        old.GetType().GetProperty(prop.Name).SetValue(old, newValue.ToString());
                    }
                }
            }
            //old.State = "Y";
            old.UpdateTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            var filter = Builders<T>.Filter.Eq("Id", entity.Id);
            ReplaceOneResult result = collection.ReplaceOneAsync(filter, old).Result;



        }

        public void Delete<T>(T entity) where T : BaseEntity
        {
            var collection = db.GetCollection<T>(typeof(T).Name);
            var filter = Builders<T>.Filter.Eq("Id", entity.Id);
            collection.DeleteOneAsync(filter);
        }
        public T QueryOne<T>(string id) where T : BaseEntity
        {
            var collection = db.GetCollection<T>(typeof(T).Name);
            return collection.Find(a => a.Id == ObjectId.Parse(id)).ToList().FirstOrDefault();
        }
        public T QueryOne<T>(string field, string value) where T : BaseEntity
        {

            var collection = db.GetCollection<T>(typeof(T).Name);
            FilterDefinition<T> filter = Builders<T>.Filter.Eq(field, value);
            return collection.Find(filter).ToList().FirstOrDefault();
        }
        public async Task<List<T>> QueryOneAsync<T>(string field, string value) where T : BaseEntity
        {

            var collection = db.GetCollection<T>(typeof(T).Name);
            FilterDefinition<T> filter = Builders<T>.Filter.Eq(field, value);
            return await collection.Find(filter).ToListAsync();
        }
        public List<T> QueryAll<T>() where T : BaseEntity
        {
            var collection = db.GetCollection<T>(typeof(T).Name);
            return collection.Find(t => true).ToList();
        }
        public List<T> QueryAll<T>(string field, string value) where T : BaseEntity
        {
            var collection = db.GetCollection<T>(typeof(T).Name);
            FilterDefinition<T> filter = Builders<T>.Filter.Eq(field, value);
            return collection.Find(filter).ToList();
        }
    }

 

发表评论