92 lines
3.2 KiB
C#

using Marco.Pms.Model.MongoDBModels;
using Microsoft.Extensions.Configuration;
using MongoDB.Bson;
using MongoDB.Driver;
using System.Collections;
namespace Marco.Pms.CacheHelper
{
public class UpdateLogHelper
{
private readonly IMongoDatabase _mongoDatabase;
public UpdateLogHelper(IConfiguration configuration)
{
var connectionString = configuration["MongoDB:ModificationConnectionString"];
var mongoUrl = new MongoUrl(connectionString);
var client = new MongoClient(mongoUrl); // Your MongoDB connection string
_mongoDatabase = client.GetDatabase(mongoUrl.DatabaseName); // Your MongoDB Database name
}
public async Task PushToUpdateLogsAsync(UpdateLogsObject oldObject, string collectionName)
{
var collection = _mongoDatabase.GetCollection<UpdateLogsObject>(collectionName);
await collection.InsertOneAsync(oldObject);
}
public async Task<List<UpdateLogsObject>> GetFromUpdateLogsByEntityIdAsync(Guid entityId, string collectionName)
{
var collection = _mongoDatabase.GetCollection<UpdateLogsObject>(collectionName);
var filter = Builders<UpdateLogsObject>.Filter.Eq(p => p.EntityId, entityId.ToString());
List<UpdateLogsObject> result = await collection
.Find(filter)
.ToListAsync();
return result;
}
public async Task<List<UpdateLogsObject>> GetFromUpdateLogsByUpdetedByIdAsync(Guid updatedById, string collectionName)
{
var collection = _mongoDatabase.GetCollection<UpdateLogsObject>(collectionName);
var filter = Builders<UpdateLogsObject>.Filter.Eq(p => p.UpdatedById, updatedById.ToString());
List<UpdateLogsObject> result = await collection
.Find(filter)
.ToListAsync();
return result;
}
public BsonDocument EntityToBsonDocument(object entity)
{
var bson = new BsonDocument();
var props = entity.GetType().GetProperties();
foreach (var prop in props)
{
var value = prop.GetValue(entity);
if (value == null)
{
bson[prop.Name] = BsonNull.Value;
continue;
}
if (value is Guid guidValue)
{
bson[prop.Name] = guidValue.ToString(); // store Guid as string
}
else if (value is string || value.GetType().IsPrimitive || value is DateTime)
{
bson[prop.Name] = BsonValue.Create(value); // simple types
}
else if (value is IEnumerable list && !(value is string))
{
var array = new BsonArray();
foreach (var item in list)
{
array.Add(EntityToBsonDocument(item)); // recursive
}
bson[prop.Name] = array;
}
else
{
// nested object
continue;
}
}
return bson;
}
}
}