Fork me on GitHub

使用MongoDB的支持Linq 驱动NoRM

MongoDB的驱动有好几个,分布式文件存储的数据库开源项目MongoDB里使用的是github.com/samus/mongodb-csharp,monogodb-csharp不是强类型,使用起来不方便。转向使用支持强类型访问MongoDB的NoRM C# driver。NoRM 驱动和MongoDB-CSharp的一个区别的地方就是NoRM使用强类型的类操作MongoDB-CSharp的Document类。

使用NoRM很简单,引用NoRM.dll就可以了,下面的例子是一个控制台程序:

image

模型类,代表保存到数据库的数据

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Norm;

namespace FirstMongoDb
{
    public class Customer: IHaveIdentifier
    {
        public ObjectId _id { get; set; }
        public string Name { get; set; }
        public DateTime LastOrderUtc { get; set; }
        public List<string> OrderedItems { get; set; }

        public Customer()
        {
            OrderedItems = new List<string>();
        }
    }
}

这个足够简单了,下面我们连到数据库

public class MongoDbDataContext : IDisposable
    {
        private readonly MongoQueryProvider provider;

        public MongoQueryProvider Provider
        {
            get { return provider; }
        }

        public static string DatabaseName { get; set; }

        public MongoDbDataContext()
        {
            if ( string.IsNullOrEmpty( DatabaseName ) )
            {
                throw new InvalidOperationException( "You must set the static DatabaseName property." );
            }
            provider = new MongoQueryProvider(
                new Mongo( DatabaseName, "127.0.0.1", "27017", null ) );
        }

使用NoRM去冬连接到数据需要提供一个数据库名,服务器地址和端口,参看上述红色代码。

插入一个对象到数据库

private static void Insert()
        {

            Customer c = new Customer();
            c.Name = "Jake";
            c.LastOrderUtc = DateTime.UtcNow;
            c.OrderedItems.Add("frappa");
            c.OrderedItems.Add( "beer" );
            c.OrderedItems.Add( "redbull!" );
            c.OrderedItems.Add( "wings" );

            using ( MongoDbDataContext ctx = new MongoDbDataContext() )
            {
                ctx.Add(c);
            }
        }

使用LINQ查询数据库

using ( MongoDbDataContext ctx = new MongoDbDataContext() )
{
                var query =
                    from c in ctx.Customers
                    where c.Name == "Michael"
                    orderby c.LastOrderUtc descending
                    select c;

                foreach (var customer in query)
                {
                    Console.WriteLine("{0} bought {1}",
                        customer.Name,
                        customer.OrderedItems.FirstOrDefault()
                        );
                }
            }

 

参考:Using MongoDB with the NoRM driver

posted @ 2010-06-04 21:02  张善友  阅读(7735)  评论(6编辑  收藏  举报