MVC——就酱紫一个系列,这是一个好的开始3

今天我们来研究一下MongoDB  一个NoSql的数据库

想了解的可以看一下 园子里面的文章 http://www.cnblogs.com/lipan/archive/2011/03/08/1966463.html

 

这里是MongoDB 支持的开发语言驱动下载

http://www.mongodb.org/display/DOCS/Drivers

 

要安装官方的MongoDB C#中的驱动程序,在运行程序包管理器控制台中执行以下命令

打开后 PM> Install-package mongocsharpdriver

等待一会

您正在从 10gen, Inc. 下载 mongocsharpdriver,有关此程序包的许可协议在 http://www.apache.org/licenses/LICENSE-2.0 上提供。请检查此程序包是否有其他依赖项,这些依赖项可能带有各自的许可协议。您若使用程序包及依赖项,即构成您接受其许可协议。如果您不接受这些许可协议,请从您的设备中删除相关组件。
已成功安装“mongocsharpdriver 1.8.3”。
已成功将“mongocsharpdriver 1.8.3”添加到 Data。

 

注意

 

要更改 默认项目

 

打开 Data项目 引用 可以发现 添加的 MongoDB驱动 dll

我们在Data 里面新建一个文件夹 Repository

 

再找这个里面我们新建一个接口 做为 数据操作的基本方法的 接口

public interface IRepo<T> : IDisposable
    {
        T Add(T item);
        void Add(IEnumerable<T> items);
        void Update(T item);
        T Single(Expression<Func<T, bool>> expression);
        T Single(long id);
        long Count();
        IEnumerable<T> All();
        IEnumerable<T> Where(Expression<Func<T, bool>> expression);
        MongoCursor<T> Find(IMongoQuery query);
        void Delete(long id);
        void Delete(Expression<Func<T, bool>> expression);
        void Delete(T item);
        void DeleteAll();
        /// <summary>
        /// 返回符合查询条件的 集合
        /// </summary>
        /// <param name="query">mongo查询条件</param>
        /// <returns></returns>
        MongoCursor<T> Where(IMongoQuery query);
        IEnumerable<BsonDocument> Group(IMongoQuery query, GroupByBuilder keyFuction, BsonDocument initial, BsonJavaScript reduce, BsonJavaScript finalize);
    }

 

我们接着 在Model 类库里面 里面添加一个类

namespace Model
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;

    /// <summary>
    /// 属性用来注释Enities与override mongo集合名称。默认情况下,此属性
    /// Attribute used to annotate Enities with to override mongo collection name. By default, when this attribute
    /// 没有被指定,类名将会被使用
    /// is not specified, the classname will be used.
    /// </summary>
    [AttributeUsage(AttributeTargets.Class, Inherited = true)]
    public class CollectionName : Attribute
    {
        /// <summary>
        /// 初始化集合名类属性与所需的名称的新实例。
        /// Initializes a new instance of the CollectionName class attribute with the desired name.
        /// </summary>
        /// <param name="value">Name of the collection  集合的名称.</param>
        public CollectionName(string value)
        {
            if (string.IsNullOrWhiteSpace(value))
            {
                throw new ArgumentException("Empty collectionname not allowed", "value");
            }

            this.Name = value;
        }

        /// <summary>
        /// Gets the name of the collection.
        /// </summary>
        /// <value>The name of the collection.</value>
        public string Name { get; private set; }
    }
}

添加一个

初始化集合名类属性与所需的名称的新实例 方法

CollectionName

 

接着在Data里面添加一个文件夹 MongoDB

这里存放和EF里面存放的是一样的 都是操作数据的 方法  和ADO.NET  差不多

首先添加一个扩展类

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Model;
using Model;
using MongoDB.Driver;

namespace Data.MongoDB
{
    /// <summary>
    /// Internal miscellaneous utility functions.
    /// </summary>
    internal static class Util
    {
        /// <summary>
        /// The default key MongoRepository will look for in the App.config or Web.config file.
        /// </summary>
        private const string DefaultConnectionstringName = "MongoDB";

        /// <summary>
        /// Retrieves the default connectionstring from the App.config or Web.config file.
        /// </summary>
        /// <returns>Returns the default connectionstring from the App.config or Web.config file.</returns>
        public static string GetDefaultConnectionString()
        {
            return ConfigurationManager.ConnectionStrings[DefaultConnectionstringName].ConnectionString;
        }

        /// <summary>
        /// Creates and returns a MongoDatabase from the specified url.
        /// </summary>
        /// <param name="url">The url to use to get the database from.</param>
        /// <returns>Returns a MongoDatabase from the specified url.</returns>
        private static MongoDatabase GetDatabaseFromUrl(MongoUrl url)
        {
            var server = MongoServer.Create( MongoServerSettings.FromUrl(url));
            return server.GetDatabase(url.DatabaseName);
        }

        /// <summary>
        /// Creates and returns a MongoCollection from the specified type and connectionstring.
        /// </summary>
        /// <typeparam name="T">The type to get the collection of.</typeparam>
        /// <param name="connectionstring">The connectionstring to use to get the collection from.</param>
        /// <returns>Returns a MongoCollection from the specified type and connectionstring.</returns>
        public static MongoCollection<T> GetCollectionFromConnectionString<T>(string connectionstring)
            where T : Entity
        {
            return Util.GetDatabaseFromUrl(new MongoUrl(connectionstring))
                .GetCollection<T>(GetCollectionName<T>());
        }

        /// <summary>
        /// Creates and returns a MongoCollection from the specified type and url.
        /// </summary>
        /// <typeparam name="T">The type to get the collection of.</typeparam>
        /// <param name="url">The url to use to get the collection from.</param>
        /// <returns>Returns a MongoCollection from the specified type and url.</returns>
        public static MongoCollection<T> GetCollectionFromUrl<T>(MongoUrl url)
            where T : Entity
        {
            return Util.GetDatabaseFromUrl(url)
                .GetCollection<T>(GetCollectionName<T>());
        }

        /// <summary>
        /// Determines the collectionname for T and assures it is not empty
        /// </summary>
        /// <typeparam name="T">The type to determine the collectionname for.</typeparam>
        /// <returns>Returns the collectionname for T.</returns>
        private static string GetCollectionName<T>() where T : Entity
        {
            string collectionName;
            if (typeof(T).BaseType.Equals(typeof(object)))
            {
                collectionName = GetCollectioNameFromInterface<T>();
            }
            else
            {
                collectionName = GetCollectionNameFromType(typeof(T));
            }

            if (string.IsNullOrEmpty(collectionName))
            {
                throw new ArgumentException("Collection name cannot be empty for this entity");
            }
            return collectionName;
        }



        /// <summary>
        /// Determines the collectionname from the specified type.
        /// </summary>
        /// <typeparam name="T">The type to get the collectionname from.</typeparam>
        /// <returns>Returns the collectionname from the specified type.</returns>
        private static string GetCollectioNameFromInterface<T>()
        {
            string collectionname;

            // Check to see if the object (inherited from Entity) has a CollectionName attribute
            var att = Attribute.GetCustomAttribute(typeof(T), typeof(CollectionName));
            if (att != null)
            {
                // It does! Return the value specified by the CollectionName attribute
                collectionname = ((CollectionName)att).Name;
            }
            else
            {
                collectionname = typeof(T).Name;
            }

            return collectionname;
        }

        /// <summary>
        /// Determines the collectionname from the specified type.
        /// </summary>
        /// <param name="entitytype">The type of the entity to get the collectionname from.</param>
        /// <returns>Returns the collectionname from the specified type.</returns>
        private static string GetCollectionNameFromType(Type entitytype)
        {
            string collectionname;

            // Check to see if the object (inherited from Entity) has a CollectionName attribute
            var att = Attribute.GetCustomAttribute(entitytype, typeof(CollectionName));
            if (att != null)
            {
                // It does! Return the value specified by the CollectionName attribute
                collectionname = ((CollectionName)att).Name;
            }
            else
            {
                // No attribute found, get the basetype
                while (!entitytype.BaseType.Equals(typeof(Entity)))
                {
                    entitytype = entitytype.BaseType;
                }

                collectionname = entitytype.Name;
            }

            return collectionname;
        }
    }
}

 

其中的引用 根据自己的添加

继续 添加的 就是MongoDB

using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using Core.Repository;
using Model;
using MongoDB.Bson;
using MongoDB.Driver;
using MongoDB.Driver.Builders;

namespace Data.MongoDB
{
    public class MongoRepo<T> : IRepo<T>
        where T : Entity, new()
    {
        /// <summary>
        /// MongoCollection field.
        /// </summary>
        private MongoCollection<T> collection;


        public MongoRepo()
            : this(Util.GetDefaultConnectionString())
        {
        }


        public MongoRepo(string connectionString)
        {
            this.collection = Util.GetCollectionFromConnectionString<T>(connectionString);
        }

        public MongoRepo(MongoUrl url)
        {
            this.collection = Util.GetCollectionFromUrl<T>(url);
        }

        [Obsolete("This property will be removed in future releases; for most purposes you can use the MongoRepositoryManager<T>.")]
        public MongoCollection<T> Collection
        {
            get
            {
                return this.collection;
            }
        }


        public long Count()
        {
            return this.collection.Count();
        }

        public T Single(long id)
        {
            return this.collection.Find(Query.EQ("_id", id)).SingleOrDefault();
        }


        public T Single(Expression<Func<T, bool>> criteria)
        {
            return this.collection.AsQueryable<T>().Where(criteria).FirstOrDefault();
        }


        public IEnumerable<T> Where(Expression<Func<T, bool>> criteria)
        {
            return this.collection.AsQueryable<T>().Where(criteria);
        }


        public IEnumerable<T> All()
        {
            return this.collection.AsQueryable<T>();
        }


        public T Add(T entity)
        {
            this.collection.Save<T>(entity);
            return entity;
        }

        public void Add(IEnumerable<T> entities)
        {
            this.collection.InsertBatch<T>(entities);
        }


        public void Update(T entity)
        {
            this.collection.Save<T>(entity);

        }

        public void Update(IEnumerable<T> entities)
        {
            foreach (T entity in entities)
            {
                this.collection.Save<T>(entity);
            }
        }


        public void Delete(long id)
        {
            this.collection.Remove(Query.EQ("_id", id));
        }


        public void Delete(T entity)
        {
            this.Delete(entity.ID);
        }


        public void Delete(Expression<Func<T, bool>> criteria)
        {
            foreach (T entity in this.collection.AsQueryable<T>().Where(criteria))
            {
                this.Delete(entity.ID);
            }
        }

        public void DeleteAll()
        {
            this.collection.RemoveAll();
        }

        public bool Exists(Expression<Func<T, bool>> criteria)
        {
            return this.collection.AsQueryable<T>().Any(criteria);
        }

        /// <summary>
        /// 分组
        /// </summary>
        /// <param name="query">分组的条件</param>
        /// <param name="keyFuction">分组的主键</param>
        /// <param name="initial">函数</param>
        /// <param name="reduce"></param>
        /// <param name="finalize"></param>
        /// <returns></returns>
        public IEnumerable<BsonDocument> Group(IMongoQuery query, GroupByBuilder keyFuction, BsonDocument initial, BsonJavaScript reduce, BsonJavaScript finalize)
        {
            return this.collection.Group(query, keyFuction, initial, reduce, finalize);
        }

        /// <summary>
        /// 返回符合查询条件的 集合
        /// </summary>
        /// <param name="query">mongo查询条件</param>
        /// <returns></returns>
        public MongoCursor<T> Where(IMongoQuery query)
        {
            return this.collection.FindAs<T>(query);
        }


        public MongoCursor<T> Find(IMongoQuery query)
        {
            return this.collection.Find(query);
        }


        public IDisposable RequestStart()
        {
            return this.RequestStart(false);
        }


        public IDisposable RequestStart(bool slaveOk)
        {
            return this.collection.Database.RequestStart(slaveOk);
        }


        public void RequestDone()
        {
            this.collection.Database.RequestDone();
        }

        public void Dispose()
        {

        }
    }
}

里面要实现之前添加 操作接口 和继承 实体的基类

 

复制的这段代码 会发现 有那么点小错误 

是因为缺少了引用 


using MongoDB.Driver.Linq;

 

以后我们大多数 都用linq来操作数据的

在Web.config

  <connectionStrings>

<add name="MongoDB" connectionString="mongodb://116.213.73.94/数据库名称" />

 

在操作数据库之前,我要说明一下:MongoDB在使用前,并不要求您事先创建好相应的数据库,设计数据表结构!
在MongoDB中,没有【表】的概念,取而代之的是【集合】,也没有【数据记录】的概念,取而代之的是【文档】, 我们可以把【文档】理解成一个【对象】,任意的对象,甚至可以有复杂的嵌套层次。

因此,我们不用再写代码从【数据表字段】到C#类的【属性,字段】的转换了,现在直接就可以读写整个对象了。
而且MongoDB不支持Join操作,所以,如果有【关联】操作,就需要你自己来处理。

 

今天就写到这里   都在学习

 

我们的QQ群:

ASP.NET零度交流群

 105568127 

 

posted @ 2013-11-28 23:31  风飞萧雪  阅读(247)  评论(0)    收藏  举报