1

I use azure Cosmos DB with MongoDB api in my .net web api project. I created entity Log and repository

public class Log : EntityBase
{
    public string LogId { get; private set; }
    public string Message { get; private set; }
    public LogTypes LogType { get; private set; }

    public Log(string message, LogTypes logType, DateTime created)
    {
        LogId = Guid.NewGuid().ToString();
        Message = message;
        LogType = logType;
        SetCreated(created);
    }

}

public abstract class EntityBase
{
    public DateTime Created { get; private set; }

    public DateTime? LastModified { get; private set; }

    public virtual void SetCreated(DateTime datetime)
    {
        Created = datetime;
    }

    public virtual void Update(DateTime datetime)
    {
        LastModified = datetime;
    }
}

public class LogRepository : ILogRepository
{
    private IMongoCollection<Log> _logs;
    public LogRepository(IApplicationNoSqlDbContext mongoContext)
    {
        var database= mongoContext.GetDatabase();
        _logs = database.GetCollection<Log>("Logs");
    }

    public async Task AddLog(Log log)
    {
        await _logs.InsertOneAsync(log);
    }
}

Above code works, but I have a problem with "Created" property. In the database, the record looks like this:

    {
        "_id" : ObjectId("6009779afd752e89fb6e0949"),
        "_t" : [
            "EntityBase",
            "Log"
        ],
        "Created" : {
            "$date" : 1611236756061
        },
        "LastModified" : null,
        "LogId" : "772d740f-d7a6-4614-8370-d2dc9c871e24",
        "Message" : "test2",
        "LogType" : 0
    }

Why is "Created" property has this format? How can I change it and store simply UTC format? I tried configure that in this way:

        BsonClassMap.RegisterClassMap<EntityBase>(cm =>
        {
            cm.SetIsRootClass(true);
            cm.AutoMap();
            cm.MapProperty(x => x.Created).SetSerializer(DateTimeSerializer.UtcInstance);
        });

But the format is the same.

David Makogon
  • 69,407
  • 21
  • 141
  • 189
piotrB
  • 145
  • 1
  • 1
  • 11

0 Answers0