您的位置:首页 > 编程语言 > C#

c#开发Mongo笔记第六篇

2016-11-02 11:41 375 查看
之前写的五篇比较得到了大家的积极反馈,也有个别高手对我写我写出的代码进行了指教。

其中提到的我写的查询方法性能有问题,我想了想,如果mongo不是延时加载的话,那我的查询就真的有问题了,就成了查询出来所有的数据再进行二次筛选了。

可能这也是之前总是使用entity framework框架导致的习惯性这么写了吧。今天赶紧进行了一下代码,现在贴出来一下,省的之前的错误写法误导了大家,再此也感谢大家对我的批评指正

public static User GetById(ObjectId id)
{
MongoDatabase db = MongoHelper.GetConnection();
MongoCollection collection = db.GetCollection<User>("User");
return    collection.FindOneByIdAs<User>(id);

}
public static User GetByName(string name)
{
MongoDatabase db = MongoHelper.GetConnection();
MongoCollection collection = db.GetCollection<User>("User");
var query = Query.And(Query.EQ("UserName", name));
return   collection.FindOneAs<User>(query);

}

public static MongoCollection GetCollection()
{
MongoDatabase db = MongoHelper.GetConnection();
return db.GetCollection<User>("User");
}

public static bool IsHasUser(IMongoQuery query)
{
MongoDatabase db = MongoHelper.GetConnection();
MongoCollection collection = db.GetCollection<User>("User");
return    collection.Count(query)>0;

}

public static void Update(IMongoQuery query,IMongoUpdate  update)
{
MongoDatabase db = MongoHelper.GetConnection();
MongoCollection collection = db.GetCollection<User>("User");
collection.Update(query, update);
}


从灵活的角度我我觉得还是都传imongoquery类型的参数吧,比直接传string 类型的字符串要灵活的多,调用这个函数的时候我通常这么写

var queryName = Query.And(Query.EQ("UserName", cwsnuser));
//验证用户是否存在
if (DALUser.IsHasUser(queryName))
{
return Content("2");//用户名重复
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: