Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do we configure conventions on Entity Framework 7?

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?

like image 206
Minduca Avatar asked Sep 12 '15 05:09

Minduca


People also ask

What is Entity Framework Convention?

Conventions are a set of rules hard-baked into Entity Framework Core that govern how the model will be mapped to a database schema. Most of the time, especially with new application development, it makes sense to follow EF Core's conventions when developing the model.

Which of the following is the default convention to configure a Primarykey property in EF 6 code first?

EF will create a primary key column for the property named Id or <Entity Class Name> + "Id" (case insensitive). By default EF will look for the foreign key property with the same name as the principal entity primary key name.

Which of the following can be used to override the default conventions?

Code-First builds the conceptual model from your domain classes using default conventions. EF 6 Code-First leverages a programming pattern referred to as convention over configuration. However, you can override these conventions by configuring your domain classes to provide EF with the information it needs.


1 Answers

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

like image 166
natemcmaster Avatar answered Oct 13 '22 00:10

natemcmaster