繁体   English   中英

使用POCO的MongoDB和Windows表单

[英]MongoDB and Windows Forms using POCO

我希望能够在使用POCO的同时将Windows Form与MongoDB一起使用,主要是因为从MongoDB轻松获取字符串文字中的值很容易。 我唯一遇到的问题是POCO将Windows窗体中的空白条目作为空白字符串(“”),因此在使用InsertOneAsync()时,我会看到带有值“”的字段。

通常这是不理想的,主要是因为:

  1. 它占用了集合中的空间,并且
  2. 我想使用Windows窗体本身进行查询。 如果查询在Mongo文档中的一个字段中包含“”,则该查询不是“”(非空字符串),则它将不返回任何内容,因为字符串不匹配。

以下是用于将文档从Windows窗体导入MongoDB的代码。我遇到的其他一些问题:

  • 使用“ null”只会创建一个值为null的字段。 我的目标仅仅是不创建该领域。
  • 我的ZIP代码将“ null”转换为“ 0”。 我想更改它,以便在Windows窗体条目为空白时不进入该字段。

      var person = new Person { lastName = textBox1.Text.ToUpper(), firstName = textBox8.Text.ToUpper(), address = new Address { streetAddress = textBox4.Text.ToUpper(), city = textBox5.Text.ToUpper(), state = comboBox1.Text.ToUpper(), ZIP = Convert.ToInt32(string.IsNullOrEmpty(textBox7.Text) ? null : textBox7.Text) } }; var client = new MongoClient(); var database = client.GetDatabase("dataBase"); var col = database.GetCollection<Person>("addressBook"); await col.InsertOneAsync(person); 

附言:这是我在这里的第一个问题,因此,如果我没有提供足够的信息,请告诉我。

因此,经过一番刻苦的搜索,看来POCO对于多字段请求不是理想的。

发出请求的最佳方法是使用BsonDocument通用类型,然后将找到的文档转换为通用类型“人”。 示例代码发布在这里:

var doc = new BsonDocument(); // Creating a filter for me in BSON

var lastName = textBox1.Text;
if (lastName != "") // Is my string in the Windows Form empty?
    doc.Add("lastName", lastName); // If not, add me to the filter.

var firstName = textBox8.Text;
if (firstName != "")
    doc.Add("firstName", firstName);

如果字符串文字不为空,则它将字段及其对应的值添加到将用作过滤器的BsonDocument中。

var doc = await colBson.Find(filter).FirstOrDefaultAsync();
// Find me, but as a BSON document.

然后找到该文档作为BsonDocument。

var person = BsonSerializer.Deserialize<Person>(doc);
// Convert me into a <Person> generic type.

在这里,您可以根据需要使用“ Person”类型的类进行操作。

如果我不清楚,请告诉我。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM