Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to customize MongoDb collection name on .Net Core Model?

I can't find annotation for MongoDb, what can in .Net Core model modify collection name. In SQL database it will be [Table("all_sessions")].

My model name and collection name are different. I have not change model or collection name.

public class Session
    {
        [BsonId]
        [BsonRepresentation(BsonType.ObjectId)]
        [BsonElement("_id")]
        public string Id { get; set; }

        [BsonElement("expires")]
        public string Expires { get; set; }

        [BsonElement("session")]
        public string Session { get; set; }
    }

My collection name is all_sessions. I expect get working Session model with all_sessions collection.

like image 848
hdoitc Avatar asked Sep 05 '25 03:09

hdoitc


1 Answers

So time ago i was fancing similar issue and i've created my own implementation of that pattern.

So first part is to create custom attribute:

[AttributeUsage(AttributeTargets.Class, Inherited = false)]
public class BsonCollectionAttribute : Attribute
{
    private string _collectionName;
    public BsonCollectionAttribute(string collectionName)
    {
        _collectionName = collectionName;
    }
    public string CollectionName => _collectionName;
}

Second part is to obtain the value of this attribute with reflection

private static string GetCollectionName()
{
    return (typeof(T).GetCustomAttributes(typeof(BsonCollectionAttribute), true).FirstOrDefault()
        as BsonCollectionAttribute).CollectionName;
}

I'am doing that in repository class, so example method from mthat class looks like that:

        public async Task InsertOne(T model)
        {
            var collectionName = GetCollectionName();
            var collection = Database.GetCollection<T>(collectionName);
            await collection.InsertOneAsync(model);
        }

In the end my model looks like:

[BsonCollection("Users")]
public class User
{
    [BsonId]
    [BsonElement("id")]
    [BsonRepresentation(BsonType.String)]
    public Guid Id { get; set; }

    [BsonElement("name")]
    public string Name { get; set; }
    [BsonElement("email")]
    public string Email { get; set; }
    [BsonElement("password")]
    public string Password { get; set; }

Hope that i've helped ;)

like image 155
Kamil Kiełbasa Avatar answered Sep 07 '25 20:09

Kamil Kiełbasa