为什么是c#和MongoDB驱动程序代码连接,但未能写
本文关键字:连接 代码 MongoDB 驱动程序 为什么 | 更新日期: 2023-09-27 18:14:10
以下是关于我的开发环境的信息:
- Microsoft Visual Studio Community 2015
- 。. NET Framework 4.6
- ASP。System.Web.Mvc版本=5.2.3.0
- MongoDB。司机2.0.1.27
- Mongodb 3.0.6
在我的c#应用程序中,我有以下代码检索MongoDB数据库引用:
public class MongoDBConnectionManager {
public IMongoDatabase getMongoDB() {
var client = new MongoClient("mongodb://localhost:27017");
MongoClient(System.Configuration.ConfigurationManager.ConnectionStrings["MongoDB"].ConnectionString);
MongoServer.Create("Server=localhost:27017");
IMongoCollection <BsonDocument> UserDetails = iMgDb.GetCollection<BsonDocument>("Users");
return iMgDb;
}
}
下面是代表用户业务实体的POCO类:
using MongoDB.Bson.Serialization.Attributes;
public class UserModel {
[BsonId]
public int ID { get; set; }
[Required]
[BsonElement]
public string UserName { get; set; }
[Required]
[BsonElement]
public string Password { get; set; }
[Required]
[BsonElement]
public string Email { get; set; }
[BsonElement]
public string PhoneNo { get; set; }
[BsonElement]
public string Address { get; set; }
}
下面是使用mongodb连接管理器类的DAO c#类:
public class DAO {
public async Task<int> insertNewUser(UserModel um) {
MongoDBConnectionManager mgoDBCntMng = new MongoDBConnectionManager();
IMongoDatabase database = mgoDBCntMng.getMongoDB();
IMongoCollection <UserModel> UserDetails = database.GetCollection<UserModel>("Users");
try {
Task getTask = UserDetails.InsertOneAsync(um);
await getTask;
} catch(Exception) {
}
return 0;
}
}
当我运行应用程序时,我可以在启动mongoDB的DOS命令提示符窗口中看到以下信息。如果你看一下Dos命令提示符的末尾,你会注意到正在进行2个连接:
C:'Program Files'MongoDB'Server'3.0'bin>mongod --dbpath ./data/db
2015-09-23T12:23:07.896+0530 I JOURNAL [initandlisten] journal
dir=./data/db'jo
urnal
2015-09-23T12:23:07.900+0530 I JOURNAL [initandlisten] recover : no
journal fil
es present, no recovery needed
2015-09-23T12:23:08.060+0530 I JOURNAL [durability] Durability thread started
2015-09-23T12:23:08.062+0530 I JOURNAL [journal writer] Journal writer thread s
tarted
2015-09-23T12:23:08.283+0530 I CONTROL [initandlisten] MongoDB starting
: pid=1
2936 port=27017 dbpath=./data/db 64-bit host=My-PC
2015-09-23T12:23:08.283+0530 I CONTROL [initandlisten] targetMinOS:
Windows 7/W
indows Server 2008 R2
2015-09-23T12:23:08.284+0530 I CONTROL [initandlisten] db version v3.0.6
2015-09-23T12:23:08.284+0530 I CONTROL [initandlisten] git version:
1ef45a23a4c
5e3480ac919b28afcba3c615488f2
2015-09-23T12:23:08.284+0530 I CONTROL [initandlisten] build info:
windows sys.
getwindowsversion(major=6, minor=1, build=7601, platform=2,
service_pack='Servic
e Pack 1') BOOST_LIB_VERSION=1_49
2015-09-23T12:23:08.285+0530 I CONTROL [initandlisten] allocator:
tcmalloc
2015-09-23T12:23:08.285+0530 I CONTROL [initandlisten] options: {
storage: { db
Path: "./data/db" } }
2015-09-23T12:23:08.321+0530 I NETWORK [initandlisten] waiting for
connections
on port 27017
2015-09-23T12:24:20.326+0530 I NETWORK [initandlisten] connection
accepted from
127.0.0.1:65065 #1 (1 connection now open)
2015-09-23T12:24:22.332+0530 I NETWORK [initandlisten] connection
accepted from
127.0.0.1:65066 #2 (2 connections now open)
我真不知道该如何解决这个问题。我试图使用DOS命令提示符搜索MongoDB错误日志,但它显示没有错误。从MongoDB客户端使用DOS命令提示符,我得到了以下内容:
C:'Program Files'MongoDB'Server'3.0'bin>mongo
MongoDB shell version: 3.0.6
connecting to: test
> use foo
switched to db foo
> db.runCommand( { getLastError: 1, w: 1, wtimeout:5000 } )
{
"connectionId" : 6,
"n" : 0,
"syncMillis" : 0,
"writtenTo" : null,
"err" : null,
"ok" : 1
}
我面临的问题是执行点运行顺利,但无法写入数据库。
我在上述代码中使用异步和等待的方式有什么问题?
From MSDN
await操作符应用于异步方法中的任务,以挂起该方法的执行,直到等待的任务完成。任务表示正在进行的工作。
所以await会挂起或阻塞直到任务完成,所以我们只是创建多个任务,并确保我们不会等待它,直到我们认为我们需要,如果你正在处理insert集合?
var tasks = new Task<//return type of UserDetails.InsertOneAsync(um)>[//get collection count here];
var count = 0;
foreach(// iterate collection here)
{
try {
tasks[count] = UserDetails.InsertOneAsync(um); // adds continuations and return back immediately i.e. no blocking
count++;
} catch(Exception) {
}
}
await Task.WhenAll(tasks.ToArray()); // here is where we block all tasks and wait for completion
注意:不是确切的答案,但会在一定程度上清楚我们在做什么
你的getMongoDB函数代码有一些问题:
- 不需要建立两个连接,只使用一个
- IMongoClient用于获取mongodb数据库。司机2.0.1.17。不需要创建"MongoServer"
- 无需在"getMongoDB"函数中获取收集
public IMongoDatabase getMongoDB()
{
IMongoClient client = new MongoClient("mongodb://localhost:27017");
var iMgDb = client.GetDatabase("Database Name Here");
return iMgDb;
}
这花了一段时间,但问题是由于我错误地使用int基本数据类型作为UserModel中的ID,而不是ObjectId。
以下是UserModel的更正代码:using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;
using MongoDB.Bson;
using MongoDB.Driver;
using MongoDB.Driver.Linq;
using WebApplication1.Models;
using MongoDB.Bson.Serialization.Attributes;
namespace WebApplication1.Models
{
public class UserModel
{
[BsonId]
public ObjectId ID { get; set; }
[Required]
[BsonElement]
public string UserName { get; set; }
[Required]
[BsonElement]
public string Password { get; set; }
[Required]
[BsonElement]
public string Email { get; set; }
[BsonElement]
public string PhoneNo { get; set; }
[BsonElement]
public string Address { get; set; }
}
}