简体   繁体   中英

How to set plural collection name in C# mongo driver?

I'm using the MongoDB default C# driver. In my code, I have created an entity (collection) with the name of Customer. Is there a default convention or class attribute that will set the pluralized version of my collection name in MongoDB ('customers') ?

I haven't found any so I'm using the Humanizer library to pluralize the names. I actually go a step further and use the type itself to create a collection:

var customers = database.GetCollection(typeof(Customer).Name.Pluralize().ToLower());

Instead of using an external library suggested by I3arnon you can use the .NET pluralizing service available in the System.Data.Entity.Design assembly.

You can use it like this:

 var serv = PluralizationService.CreateService(new System.Globalization.CultureInfo("en-us"));
 var plural = serv.Pluralize(typeof(Person).Name);

It will correctly pluralize Person to People or Customer to Customers like in the example above. It is the same mechanism used by Entity Framework pluralization.

I ran across this same issue, so I wrote a simple wrapper around the .NET MongoDB driver to automate object to collection name mapping. It uses System.Data.Entity.Design.PluralizationServices under the hood, so it doesn't rely on any external dependencies. It may save you a few lines of code.

If you're interested: https://github.com/MikePennington/Mongonizer

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM