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?
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With