.NET C#操作MongoDB异常


  • 註冊用戶

    C#操作MongoDB报错,代码如下:

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    using MongoDB.Driver;
    using MongoDB.Bson;

    namespace WindowsFormsApplication2
    {
    public partial class Form1 : Form
    {
    public Form1()
    {
    InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {

    }
    string uname = string.Empty;
    private void findall()
    {

    MongoServer mongodb = MongoServer.Create("mongodb://sa:dba@localhost:27017"); // 连接数据库
    MongoDatabase mongoDataBase = mongodb.GetDatabase("test"); // 选择数据库名
    MongoCollection mongoCollection = mongoDataBase.GetCollection("user2"); // 选择集合,相当于表
    MongoCursor<PersonEntity> user2 = mongoCollection.FindAllAs<PersonEntity>();
    String arr = String.Empty;
    int n = 0;
    foreach (PersonEntity person2 in user2)
    { arr = person2.name + "!"; n++; }
    PersonEntity person2;
    person2.name = null;
    uname= textBox1.Text += arr;
    textBox1.Text += "\r\n";
    findMath(uname);

    }
    public class PersonEntity
    {
    public ObjectId _id { get; set; }
    public string name { get; set; }
    public string flie2 { get; set; }
    public string ppath { get; set; }
    }//数据表模型

    public void findMath(string zname)
    {
    MongoServer mongodb = MongoServer.Create("mongodb://sa:dba@localhost:27017"); // 连接数据库
    MongoDatabase mongoDataBase = mongodb.GetDatabase("test"); // 选择数据库名
    MongoCollection mongoCollection = mongoDataBase.GetCollection("user2"); // 选择集合,相当于表
    QueryDocument query = new QueryDocument("name", zname);
    PersonEntity user2 = mongoCollection.FindAs<PersonEntity>(query).FirstOrDefault();
    textBox1.Text += user2.name; //到这行报错了,提示未将对象引用到对象实例
    textBox1.Text += "\r\n";
    textBox1.Text += user2.flie2;
    textBox1.Text += "\r\n";
    textBox1.Text += user2.ppath;
    textBox1.Text += "\r\n";

    }

    private void textBox1_TextChanged(object sender, EventArgs e)
    {

    }

    private void button1_Click(object sender, EventArgs e)
    {
    findall();
    }

    }
    }


  • Lv 1

    @oughl0007 說:

    PersonEntity user2 = mongoCollection.FindAs(query).FirstOrDefault(); textBox1.Text += user2.name; //到這行報錯了,提示未將對象引用到對象實例

      應該是沒查找到資料. user2 返回 null


登录后回复
 

与 萌阔论坛 的连接断开,我们正在尝试重连,请耐心等待