-
Notifications
You must be signed in to change notification settings - Fork 1
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:
- 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");
});
}
}
}I'm not going to explain here all the things you can do inside OnModelCreating, but you can find more than enough information online.