Entity framework 4 – Part 3 – Adding pluralization support to a non strongly typed ObjectContext.

Part 1 – Getting started
Part 2 – Relationships between non public members

This is a post that continues on my previous post about how you could be building a ObjectContext in Entity Framework 4, without having them to be strongly typed. There’s no EDMX model etc. in your solutions.

This time I’m just going to show you have you can consume the PluralizationService to automatically get pluralized strings. I’m using it to get pluralized tablenames from my Entity framework-based, Entity store.

Download a complete example here. Ensure to update the config-file.

To pluralize the tables I need to consume the PluralizationService from Microsoft. This is really easy. Just call the factorymethod “CreateService” and provide for which culture you wan’t it to handle strings for and then let it pluralize a string.

var pluralizer = PluralizationService.CreateService(CultureInfo.GetCultureInfo("en"));

string pluralized = pluralizer.Pluralize("UserAccount"); //Results in the string "UserAccounts"

Pluralize tablenames
This is done in my RegisterEntity method in my custom ObjectContextBuilder. The RegisterEntity method is there to let you register EntitySets in the ContextBuilder as well as register mapping information for entities; so that when the builder creates an ObjectContext, this information is passed along to the context.

/// <summary>
/// Registers the entity by setting up a set and configurations for it.
/// If no configuration is passed, only a Set will be registrered.
/// </summary>
/// <typeparam name="TEntity">The type of the entity.</typeparam>
/// <param name="entityConfiguration">The entity configuration.</param>
public void RegisterEntity<TEntity>(EntityConfiguration<TEntity> entityConfiguration = null)
    where TEntity : class, IEntity
{
    var pluralizedSetName = _pluralizer.Pluralize(typeof (TEntity).Name);

    RegisterSet<TEntity>(pluralizedSetName);
    if (entityConfiguration != null)
        Configurations.Add(entityConfiguration);
}

Above you can see that we are consuming the PluralizationService instance that has been created in the constructor. The SetName matches the name of the Entity but it is now is pluralized which leads to that the tables that are generated in the database, will have names that are pluralized.

The PluralizationService is for now found in System.Data.Entity.Design.

Download a complete example here. Ensure to update the config-file.

//Daniel