设为首页 收藏本站
查看: 853|回复: 0

[经验分享] ASP.NET MVC3和MongoDB数据库官方驱动的一个小例子

[复制链接]

尚未签到

发表于 2015-7-7 08:30:04 | 显示全部楼层 |阅读模式
11.5留言:C#

11.5.1 安装C#驱动程序
  C#驱动程序就是一个dll文件,可以从Github(https://github.com/mongodb/mongo-csharp-driver/downloads)上下载。网站上提供msi和zip压缩包两种格式。前者需要安装(自解压)后者需要用解压缩软件解压,根据个人喜欢自行选择,不管选择何种格式最好得到都是一样的。
  这里我们选择zip格式,下载和选择合适的地方解压后得到两个文件MongoDB.Bson.dll和MongoDB.Driver.dll。其中MongoDB.Bson.dll是提供BSON序列化另外一个与数据库通信,我们需要添加这两个dll到项目的引用中。

11.5.2 使用C#驱动程序
  我们需要使用添加MongoDB.Driver这个命名空间的引用来与MongoDB服务端通信:



using MongoDB.Driver;

namespace IntroMongo.Models
{
    public class MongoWrapper
    {
        public static MongoDatabase GetDatabase()
        {
            MongoServerSettings settings = new MongoServerSettings();
            settings.Server = new MongoServerAddress("localhost", 27017);
            MongoServer server = new MongoServer(settings);
            var database = server.GetDatabase("MessageDB");
            return database;
        }
    }
}
  这里,我们需要创建了一个服务器对象,并且需要设置连接字符串,端口等信息。在这个例子中,我们使用localhost作为数据库服务器地址,27017作为服务器端口,MessageDB作为数据库名称(这里最好称为集合)。

11.5.3 对象的序列化
  该驱动支持文档对象序列化,只需在字段上加上相应的注解就可以完成文档库到对象的映射。这个例子中我们有两个对象:用户和评论。具体设计如下:
  1.User



using MongoDB.Bson.Serialization.Attributes;
using MongoDB.Driver;
using MongoDB.Bson;

public class User
{
    public User()
    {
        Remarks = new List();
    }

    public ObjectId id { get; set; }
    [BsonElementAttribute("firstname")]
    public string FirstName { get; set; }
    [BsonElementAttribute("lastname")]
    public string LastName { get; set; }
    [BsonElementAttribute("age")]
    public int Age { get; set; }
    [BsonElementAttribute("createdate")]
    public DateTime CreateDate { get; set; }
    [BsonElementAttribute("remarks")]
    public IList Remarks { get; set; }

    public string GetFullName()
    {
        return String.Format("{0} {1}", FirstName, LastName);
    }
}
  2.Remark



using MongoDB.Bson.Serialization.Attributes;

public class Remark
{
    [BsonElementAttribute("content")]
    public string RemarkContent;
    [BsonElementAttribute("date")]
    public DateTime Date;
}
11.5.4 查询
  C#官方驱动提供多种方法来访问和处理数据库,具体可以查看驱动包中CSharpDriverDocs.chm说明文档。这里我们需要查询到所有用户的集合并按照创建时间倒序显示。



var users = database.GetCollection("users").
FindAll().
SetSortOrder(SortBy.Descending("createdate"));

foreach (var user in users)
{
    var userName = user["firstname"].AsString;
    ...
}
  当然我们也可以写个稍微复杂点的查询,比如:用户名以大写字母E开头,而且创建时间必须在近7天,那么查询方法应该这么的写:



var query = Query.And(
                Query.Matches("firstname", BsonRegularExpression.Create("^e")),
            Query.GT("createdate",
BsonValue.Create(DateTime.Now.AddDays(-7).Date)));

var users = database.
                GetCollection("users").
                Find(query).
                SetSortOrder(SortBy.Descending("createdate"));
11.5.5 编辑
  数据的编辑分为两个步骤首先从数据库查询数据绑定到页面表单中,显示给用户供用户修改。



var objectId = ObjectId.Parse(id);
var user = MongoWrapper.GetDatabase().
                     GetCollection("users").
                     FindOneByIdAs(ObjectId.Parse(id));
  用户提交修改后的信息时候,这时候只需调用保存更新方法“SAVE”即可完成编辑。



var user = users.FindOneById(ObjectId.Parse(id));
user["firstname"] = userToEdit.FirstName;
user["lastname"] = userToEdit.LastName;
user["age"] = userToEdit.Age;
users.Save(user);
  这里FindOneById方法获取的是一个BsonValue,其中传递的参数id需要调用ObjectId.Parse方法将string转为ObjectId。
  

11.5.6 插入
  往数据库中写入数据时候需要创建一个新的BsonDocument,并添加到集合中去。最后通过调用“INSERT”方法写入数据库,添加用户的方法如下:



var users = database.GetCollection("users");
var user = new BsonDocument();
user["firstname"] = userToEdit.FirstName;
user["lastname"] = userToEdit.LastName;
user["age"] = userToEdit.Age;
user["createdate"] = DateTime.Now;
users.Insert(user);
11.5.7删除
  删除一条记录,只需根据id去删除就可以了,具体如下:



users.Remove(Query.EQ("_id", new BsonObjectId(id)));
11.5.8 用户评论动态构建
  首先要明确一点并不是每个用户都有评论,一个用户可以有多个评论。之前我们在BsonDocument添加一个值得时候,字段都是根据所给的值动态创建的,比如:



user["age"] = 18;
  这里age将被动态创建,age的类型是Int32.当然如果你要检查话可以通过调用Contains对象的方法来确定一下,例如:



if (user.Contains("updatedate") && user["updatedate"].IsDateTime)
{
    var updatedate = user["updatedate"].AsDateTime;
}
  下面我们来看看任何给用用户添加评论,如下:



[HttpPost]
public ActionResult Index(string id, string newRemark)
{
    var users = database.GetCollection("users");
    var user = users.FindOneById(ObjectId.Parse(id));

    var remark = new BsonDocument().
                        Add("content", newRemark).
                        Add("date", DateTime.Now);
    if (user.Contains("remarks"))
    {
        user["remarks"].AsBsonArray.Add(BsonValue.Create(remark));
    }
    else
    {
        user["remarks"] = new BsonArray().Add(BsonValue.Create(remark));
    }
    users.Save(user);
    return RedirectToAction("Index", new { id = id });
}
  首先,我们需要检查用户对象中是否已经存在一个remarks的key,这里remarks实际上是个数组里面可能存有多条留言,每条留言有content和data两个key。如果remarks存在的话我们就继续添一个新的remark到remarks数组中,如果不存在的话我们需要创建一个新的数组然后添加。这样从数据库查询得到数据库结构将会得到类似这样的一个结果:



{
    "_id" : ObjectId("4ea51941073d601758138560"),
    "firstname" : "ercan",
    "lastname" : "anlama",
    "age" : 26,
    "createdate" : ISODate("2011-10-24T07:52:33.29Z"),
    "remarks" :
        [
            {
                "content" : "this is my first remark",
                "date" : ISODate("2011-10-24T07:53:22.511Z")
            }
        ]
}
11.5.9 写在最后的话
  这篇文章对MongoDB和C#的官方驱动做了一个大概的介绍,当然这些都是一些最基本的东西,属于必须要掌握的东西。
  此为MongoDB还提供更强大的功能,如GridFS和MapReduce。这些功能或许能对你现在所专注的领域能起到一定的帮助。
  本文参考CodeProject上Using MongoDB with the Official C# Driver文章加上自己理解谈不上翻译,简单的写写。
  
  原文作者:Ercan Anlama(Turkey)
  作者简介:I started to development during university years and worked in many freelance projects. I am working in software development more than 4 years and currently, working as analyst software developer in an Holland centre company in Istanbul, Turkey. I am interested in innovation and creativity in software development and passionate in learning new stuff.
  原文网址:http://www.codeproject.com/KB/database/MongoDBWithOfficeDriver.aspx
  License
  版权归原作者所有。
  This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)
  源代码可以前往codeproject下载,或者我从我这里下载
  下载地址:源码  官方驱动1.3.1

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-83945-1-1.html 上篇帖子: MongoDB使用方法 下篇帖子: MongoDB性能篇
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表