Skip to content

Creating ModelConfiguration

Eros Stein edited this page Jan 6, 2017 · 3 revisions

Sometimes we might need to tell Entity Framework how to handle some more specialized relationships. Instead of adding all the code for all our classes inside one single OnModelCreating(System.Data.Entity.DbModelBuilder) we can just create a ModelConfiguration class for every POCO that needs extra customization. Here's how to do it:

  1. Right-click your ModelConfiguration folder inside the Domain project and select Add > New Item
  2. Select Blayer and choose Model Configuration
  3. Use the same name you used for the POCO class screen shot 2017-01-06 at 17 01 51

A file is created with a similar content to this one:

using Blayer.Data;

namespace Your.Namespace.Domain.ModelConfiguration
{
    /// <summary>
    /// Model configuration (relationship) for the entity User
    /// </summary>
    public class UserModelConfiguration : IModelConfiguration
    {
        /// <summary>
        /// Configures the model for User
        /// </summary>
        /// <param name="modelBuilder">Model builder</param>
        public void Configure(System.Data.Entity.DbModelBuilder modelBuilder)
        {
            
        }
    }
}

Now we can start to add our customizations:

Many-to-many

Let's say we need to implement many-to-many relationship. One user has many groups and groups have many users. This is how we would do it:

using Blayer.Data;

namespace Your.Namespace.Domain.ModelConfiguration
{
    /// <summary>
    /// Model configuration (relationship) for the entity User
    /// </summary>
    public class UserModelConfiguration : IModelConfiguration
    {
        /// <summary>
        /// Configures the model for User
        /// </summary>
        /// <param name="modelBuilder">Model builder</param>
        public void Configure(System.Data.Entity.DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity<User>()
                .HasMany(u => u.Groups)
                .WithMany(g => g.Members)
                .Map(k =>
                {
                    k.MapLeftKey("UserId");
                    k.MapRightKey("GroupId");
                    k.ToTable("MembersOfGroups", "MySchema");
                });
        }
    }
}

After that is done we need to go back to our repository class and tell it to use this model configuration. Like this:

using Blayer.Data;
using Your.Namespace.Poco;

namespace Your.Namespace.Domain.Repositories
{
    public class UserRepository : Repository<User>
    {
        public override IModelConfiguration GetConfiguration()
        {
            return new ModelConfiguration.UserModelConfiguration();
        }
    }
}

That's it, now Blayer.Data knows about this customization.

I'm not going to explain here all the things you can do with OnModelCreating, but you can find more than enough information online.

Clone this wiki locally