Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do not insert field if null or empty

Tags:

c#

mongodb

I have a C# class with some fields and some of them are null. Those that are null I do not want to be inserted into db with null value. I do not want them inserted into db at all. How do I achieve that?

class User
{
    public string FirstName;
    public string LastName;
    public string MidName;
}

Not every user has a MidName, but Mongo inserts into db with null value on MidName field.

like image 378
raresm Avatar asked Jan 09 '15 09:01

raresm


1 Answers

Using the aptly named [BsonIgnoreIfNull] attribute:

class User
{
    public string FirstName;
    public string LastName;
    [BsonIgnoreIfNull]
    public string MidName;
}
like image 153
CodeCaster Avatar answered Oct 03 '22 19:10

CodeCaster