MongoDB c# 驱动程序覆盖字符串的默认值从 null 到 string.empty [英] MongoDB c# driver override Default value of string from null to string.empty

查看:61
本文介绍了MongoDB c# 驱动程序覆盖字符串的默认值从 null 到 string.empty的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 10gen mondgo db c# 驱动程序.我有以下课程

Using 10gen mondgo db c# driver.I have following class

[BsonId]
public ObjectId Id { get; set; }
public int AttemptId { get; set; }
public int UserId { get; set; }
public int QId { get; set; }
public string UserInput { get; set; }  
public string Feedback{ get; set; }

默认情况下,如果我不发送 UserInput 或反馈(任何字符串)的值,mongodb 会将它们作为 null .有什么方法可以在插入或获取数据时用 string.empty 覆盖它.尝试设置 [BsonDefaultValue("")] 但这也不起作用.

By default if i dont sent values of UserInput or Feedback (any string ) mongodb put them as null . Is there any way to override this with string.empty while inserting or while fetching the data. Tried setting [BsonDefaultValue("")] but this also didnt work.

推荐答案

[BsonDefaultValue("")] 仅适用于从数据库中读取没有对应字段值的文档.如果希望在内存中创建的新对象具有 null 以外的值,则需要在构造函数中设置该值.此外,当您将一个对象保存到数据库时,如果该字段为空,那么这就是保存和读回的内容.

[BsonDefaultValue("")] applies only when reading a document from the database that doesn't have a value for the corresponding field. If you want new objects you create in memory to have a value other than null you need to set that value in your constructor. Also, when you save an object to the database if the field is null then that is what is saved and read back.

因此只需在构造函数中设置默认值来处理在内存中创建的新对象(并且可能插入到数据库中),并使用 [BsonDefaultValue] 来处理可能没有相应字段的回读文档.

So just set the default value in your constructor to handle new objects created in memory (and presumably inserted to the database) and use [BsonDefaultValue] to handle reading back documents that might not have a corresponding field.

这篇关于MongoDB c# 驱动程序覆盖字符串的默认值从 null 到 string.empty的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆