使用NoRM操作MongoDB

NoRM是.NET平台下MongoDB的第三方驱动,可以使用强类型的类操作MongoDB。使用NoRM非常简单,只需要在工程中引用Norm.dll即可。下面来看一个例子。

首先建立一个表示人员信息的模型

View Code
class Person
{
[MongoIdentifier]
public string ID
{
get
{
return _id;
}
}
public string Name { get ; set ; }
public int Age { get ; set ; }
public List < string > Phone { get ; set ; }

private string _id;

public Person()
{
_id
= Guid.NewGuid().ToString();
Phone
= new List < string > ();
}

public void AddPhone( string phone)
{
Phone.Add(phone);
}
}

 接下来连接数据库

View Code
using (var db = new Mongo( " Person " , " 127.0.0.1 " , " 27017 " , null ))
{
var personColl
= db.Database.GetCollection < Person > ( " Person " );
}

 新增数据并显示

View Code
Person person1 = new Person();
person1.Name
= " Person1 " ;
person1.Age
= 1 ;
person1.AddPhone(
" 13500000001 " );
person1.AddPhone(
" 13500000002 " );

Person person2
= new Person();
person2.Name
= " Person2 " ;
person2.Age
= 2 ;
person2.AddPhone(
" 13500000003 " );
person2.AddPhone(
" 13500000004 " );

personColl.Insert(person1);
personColl.Insert(person2);
ShowPersonList(personColl);

显示部分代码如下:

View Code
private static void ShowPersonList(IMongoCollection < Person > personColl)
{
foreach (Person person in personColl.AsQueryable())
{
Console.WriteLine(
" Person Name is {0}, age is {1} " , person.Name, person.Age.ToString());
string phoneInfo = " Phone Numbers: " ;
foreach (var phone in person.Phone)
{
phoneInfo
+= phone + " " ;
}
Console.WriteLine(phoneInfo);
}
Console.WriteLine(
" Person Numbers:{0} " , personColl.Count());
}

修改数据

View Code
person2.Phone.RemoveAt( 0 );
person2.Age
= 3 ;
personColl.Save(person2);
ShowPersonList(personColl);

删除数据

View Code
personColl.Delete < Person > (person1);
ShowPersonList(personColl);

结果显示如下:

使用NoRM操作MongoDB

你可能感兴趣的:(mongodb)