首页 > 代码库 > MongoRepository

MongoRepository

起步

现在已经非常擅长使用Repository方式开发关系数据库的程序了,但是在使用Nosql如Mongo的时候,更多的是使用Mongo Driver,无意中看到了MongoRepository,允许了以Repository的方式去开发使用Mongo了。

1.新建项目通过NuGet 引入MongoRepository ;

2.我们使用的是Console application新建一个App.config,添加如下信息:

<?xml version="1.0" encoding="utf-8" ?><configuration>  <connectionStrings>    <add name="MongoServerSettings"         connectionString="mongodb://localhost/SampleProject" />  </connectionStrings></configuration>

这里保证了程序连接到我们的名字为:SampleProject的Mongo上,如果不存在SampleProject系统则会自动帮助我们创建SampleProject

 

定义业务模型

建立业务model集成Entity,这样程序会见Model文件对应到Mongo之中,创建Customer及product:

using System.Collections.Generic;using MongoRepository;public class Customer : Entity  //Inherit from Entity!{    public string FirstName { get; set; }    public string LastName { get; set; }    public List<Product> Products { get; set; }    public Customer()    {        this.Products = new List<Product>();    }}public class Product //No need to inherit from Entity; This object is not contained in                     //it‘s "own" MongoDb document. It is only contained in a customer{    public string Name { get; set; }    public decimal Price { get; set; }}

程序会自动为每个继承自Entity的model创建一个string类型的属性:Id。

如何使用

建立连接,定义model之后就可以以Repository的方式使用Mongo了。

using System;using System.Linq;using MongoRepository;class Program{    static MongoRepository<Customer> customerrepo = new MongoRepository<Customer>();    static void Main(string[] args)    {        //Add customers        var john = new Customer() { FirstName = "John", LastName = "Doe" };        var jane = new Customer() { FirstName = "Jane", LastName = "Doe" };        var jerry = new Customer() { FirstName = "Jerry", LastName = "Maguire" };        customerrepo.Add(new[] { john, jane, jerry });        //Show contents of DB        DumpData();        //Update customers        john.FirstName = "Johnny";  //John prefers Johnny        customerrepo.Update(john);        jane.LastName = "Maguire";  //Jane divorces John and marries Jerry        customerrepo.Update(jane);        //Delete customers        customerrepo.Delete(jerry.Id);  //Jerry passes away        //Add some products to John and Jane        john.Products.AddRange(new[] {                new Product() { Name = "Fony DVD Player XY1299", Price = 35.99M },                new Product() { Name = "Big Smile Toothpaste", Price = 1.99M }        });        jane.Products.Add(new Product() { Name = "Life Insurance", Price = 2500 });        customerrepo.Update(john);        customerrepo.Update(jane);        //Or, alternatively: customerrepo.Update(new [] { john, jane });        //Show contents of DB        DumpData();        //Finally; demonstrate GetById and First        var mysterycustomer1 = customerrepo.GetById(john.Id);        var mysterycustomer2 = customerrepo.First(c => c.FirstName == "Jane");        Console.WriteLine("Mystery customer 1: {0} (having {1} products)",                mysterycustomer1.FirstName, mysterycustomer1.Products.Count);        Console.WriteLine("Mystery customer 2: {0} (having {1} products)",                mysterycustomer2.FirstName, mysterycustomer2.Products.Count);        //Delete all customers        customerrepo.DeleteAll();        //Halt for user        Console.WriteLine("Press any key...");        Console.ReadKey();    }    private static void DumpData()    {        //Print all data        Console.WriteLine("Currently in our database:");        foreach (Customer c in customerrepo)        {            Console.WriteLine("{0}\t{1}\t has {2} products",                c.FirstName, c.LastName, c.Products.Count);            foreach (Product p in c.Products)                Console.WriteLine("\t{0} priced ${1:N2}", p.Name, p.Price);            Console.WriteLine("\tTOTAL: ${0:N2}", c.Products.Sum(p => p.Price));        }        Console.WriteLine(new string(‘=‘, 50));    }}

执行结果:

Currently in our database:John    Doe      has 0 products        TOTAL: $0,00Jane    Doe      has 0 products        TOTAL: $0,00Jerry   Maguire  has 0 products        TOTAL: $0,00==================================================Currently in our database:Jane    Maguire  has 1 products        Life Insurance priced $2.500,00        TOTAL: $2.500,00Johnny  Doe      has 2 products        Fony DVD Player XY1299 priced $35,99        Big Smile Toothpaste priced $1,99        TOTAL: $37,98==================================================Mystery customer 1: Johnny (having 2 products)Mystery customer 2: Jane (having 1 products)Press any key...

文件下载:http://download-codeplex.sec.s-msft.com/Download/Release?ProjectName=mongorepository&DownloadId=894208&FileTime=130528383908000000&Build=20941

MongoRepository