-
Notifications
You must be signed in to change notification settings - Fork 1
Creating ModelConfiguration
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:
- Right-click your ModelConfiguration folder inside the Domain project and select
Add > New Item - Select Blayer and choose Model Configuration
- Use the same name you used for the POCO class
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:
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.