Skip to content

Commit 6458854

Browse files
author
Giorgio Tresoldi
committed
added MongoDbCollectionNameAttribute
1 parent ac6b2d5 commit 6458854

2 files changed

Lines changed: 23 additions & 1 deletion

File tree

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
using System;
2+
3+
namespace SharpRepository.MongoDbRepository
4+
{
5+
[AttributeUsage(AttributeTargets.Class)]
6+
public class MongoDbCollectionNameAttribute: Attribute
7+
{
8+
public string CollectionName { get; }
9+
10+
public MongoDbCollectionNameAttribute(string collectionName)
11+
{
12+
CollectionName = collectionName;
13+
}
14+
}
15+
}

SharpRepository.MongoDbRepository/MongoDbRepositoryBase.cs

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ namespace SharpRepository.MongoDbRepository
2222
public class MongoDbRepositoryBase<T, TKey> : LinqRepositoryBase<T, TKey> where T : class, new()
2323
{
2424
private readonly string _databaseName;
25+
private string _collectionName;
2526
protected IMongoDatabase Database;
2627
static readonly object _lock = new object();
2728

@@ -107,11 +108,17 @@ private void Initialize(IMongoDatabase mongoDatabase = null)
107108
}
108109
);
109110
}
111+
112+
var collectionNameAttributes = EntityType.GetTypeInfo().GetOneAttribute<MongoDbCollectionNameAttribute>(inherit: true);
113+
if (collectionNameAttributes != null)
114+
_collectionName = collectionNameAttributes.CollectionName;
115+
else
116+
_collectionName = TypeName;
110117
}
111118

112119
private IMongoCollection<T> BaseCollection()
113120
{
114-
return Database.GetCollection<T>(TypeName);
121+
return Database.GetCollection<T>(_collectionName);
115122
}
116123

117124
protected override IQueryable<T> BaseQuery(IFetchStrategy<T> fetchStrategy = null)

0 commit comments

Comments
 (0)