【问题标题】:Setting a default DateTime.Now value to save to MongoDB when Document is saved保存文档时设置默认的 DateTime.Now 值以保存到 MongoDB
【发布时间】:2018-02-17 06:17:01
【问题描述】:

我是 C# 的新手,来自 ruby​​ 世界,ruby mongodb 驱动程序为所有有关保存和更新的文档提供了created_atupdated_at 字段。不幸的是,在网上搜索后,这似乎在 c# 中并不常见。

我想知道如何在持久化时将文档CreatedAt 字段默认为Time.Now

using System;
using System.Collections.Generic;
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
using MongoDB.Driver;

namespace MongoDBConsole
{
    class Program
    {
        public static void Main(string[] args)
        {
            var client = new MongoClient("mongodb://localhost:27017");
            var database = client.GetDatabase("mongodb_console");
            var collection = database.GetCollection<Person>("person");
            var person = new Person
            {
                Name = "John Doe",
                Age = 25
            };
            collection.InsertOne(person);

        }
    }

    class Person
    {
        public string Name { get; set; }
        [BsonIgnoreIfNull]
         public int? Age { get; set; }
        [BsonDefaultValue(DateTime.Now)] // <-- this errors out
        private DateTime CreatedAt { get; set; }
    }
}

编辑:

我问这个问题的目的是防止我每次实例化一个新的Person 类对象时都必须添加一个CreatedAt 字段。每当 Person 类持久化到 MongoDB 时,应自动设置 CreatedAt。每次保存文档时都可以轻松设置它,但这不是很干。我希望复制另一种编程语言中存在的功能。

【问题讨论】:

标签: c# mongodb


【解决方案1】:

今天遇到了这个,

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using MongoDB.Bson.Serialization.Attributes;

namespace NotebookAppApi.Models
{
    public class Note
    {
        [BsonId]
        public string Id { get; set; }
        public string Body { get; set; } = string.Empty;
        public DateTime UpdatedOn { get; set; } = DateTime.Now;
        public DateTime CreatedOn { get; set; } = DateTime.Now;
        public int UserId { get; set; } = 0;
    }
}

根据以下博客

Using MongoDB .NET Driver with .NET Core WebAPI

【讨论】:

  • 当你从数据库中获取数据时,模型也会将日期时间设置为当前日期时间。
【解决方案2】:

以下代码将对您有所帮助,

var person = new Person
            {
                Name = "John Doe",
                Age = 25,
                CreatedAt = DateTime.Now
            };

还将CreatedAt 属性设置为DateTime.Now

【讨论】:

  • 重点是少写代码。不幸的是,这并没有回答我的问题。我可以通过 [BsonDefaultValue("abc")] 设置默认字符串值,但默认情况下无法添加 Date 对象是没有意义的。我不想在每次创建新文档时显式添加创建时间。
  • 您不能对属性执行此操作,因为它们只是在编译时生成的元信息。如果需要,只需将代码添加到构造函数以初始化日期,创建触发器并处理数据库中的缺失值,或者以返回 DateTime 的方式实现 getter。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-06-20
  • 2017-07-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-28
  • 1970-01-01
相关资源
最近更新 更多