Set class collection name

70 views
Skip to first unread message

Alex Brown

unread,
Jul 16, 2012, 7:30:05 AM7/16/12
to mongodb...@googlegroups.com
By default, if I have a class called "MyClass" it is serialized into a collection called "myclass"

Is there a way of overriding this in the BsonClassMap?
For example, an attribute on the class, or a Convention?

If not, I'm happy to fork this and try and implement.
Just don't want to double up...

craiggwilson

unread,
Jul 16, 2012, 8:23:09 AM7/16/12
to mongodb...@googlegroups.com
That doesn't currently exist and you must specify this value everytime.  There is a Jira for this feature:  https://jira.mongodb.org/browse/CSHARP-126. It is important, vote it up or leave a comment.

NASAVIETNAM

unread,
Jul 18, 2012, 4:38:00 AM7/18/12
to mongodb...@googlegroups.com


[AttributeUsage(AttributeTargets.Class, Inherited = true)]
    public class CollectionName : Attribute
    {
        /// <summary>
        /// Initializes a new instance of the CollectionName class attribute with the desired name.
        /// </summary>
        /// <param name="value">Name of the collection.</param>
        public CollectionName(string value)
        {
            if (string.IsNullOrWhiteSpace(value))
            {
                throw new ArgumentException("Empty collectionname not allowed", "value");
            }

            Name = value;
        }

        /// <summary>
        /// Gets the name of the collection.
        /// </summary>
        /// <value>The name of the collection.</value>
        public string Name { get; private set; }
    }

//use


[CollectionName("myclass")]
public class MyClass
{

}

///

 public static string GetCollectionName<T>()
        {
            var _att = Attribute.GetCustomAttribute(typeof(T), typeof(CollectionName));
            string _collectionName = _att != null ? ((CollectionName)_att).Name : typeof(T).Name;

            if (string.IsNullOrEmpty(_collectionName))
            {
                throw new ArgumentException("Collection name cannot be empty for this entity");
            }
            return _collectionName;
Reply all
Reply to author
Forward
0 new messages