How do we configure conventions on Entity Framework 7?

ef-code-first entity-framework entity-framework-core

Question

Before EF7 I used the snipet below to remove conventions:

protected override void OnModelCreating(DbModelBuilder builder)
{
      builder.Conventions.Remove<NavigationPropertyNameForeignKeyDiscoveryConvention>();
      builder.Conventions.Remove<PrimaryKeyNameForeignKeyDiscoveryConvention>();
      builder.Conventions.Remove<PluralizingTableNameConvention>();
      builder.Conventions.Remove<PrimaryKeyNameForeignKeyDiscoveryConvention>();
      builder.Conventions.Remove<TypeNameForeignKeyDiscoveryConvention>();
}

How do we achieve the same result on Entity Framework 7?

Accepted Answer

The API for conventions isn't currently stable. See https://github.com/aspnet/EntityFramework/issues/2589.

It can be done, but it requires using dependency injection to override the internal workings of how OnModelCreating is called on your context. DbContext uses dependency injection to find an instance of ModelSource which provides the model builder (and the conventions).

To override the model source, add your own implementation into dependency injection:

    var serviceCollection = new ServiceCollection();
    serviceCollection
        .AddEntityFramework()
        .AddSqlServer();
    serviceCollection.AddSingleton<SqlServerModelSource, MyModelSource>();
    var serviceProvider = serviceCollection.BuildServiceProvider();

    using(var context = new MyContext(serviceProvider))
    {
        // ...
    }

Your implementation of MyModelSource should override ModelSource.CreateConventionSet(). See the original source here



Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why