Allow applications to create model building conventions (aka public conventions)
- [x] Create public interfaces for metadata API to be used by conventions.
- [x] Change
QueryFilter,DefiningQuery,IsEagerLoaded,IsShadowProperty,IsIndexedProperty,BeforeSaveBehaviorAfterSaveBehaviorto extension methods. - [x] Throw when calling
SetFieldwould change the shadowness of a property or the name of the identifyingMemberInfo. - [x] Rename
GetContainingPrimaryKeytoFindContainingPrimaryKey. - [x] Throw when calling
SetFieldon a shadow or a field-only property. - [x] Create public interfaces that the internal model builders implement, e.g.
IConventionModelBuilder. This will allow cleaner API, without the explicitConfigurationSourceparameter. - [x] Throw instead of silently failing when a non-explicit configuration call is invalid. This would require adding quiz API ('CanSet').
- [x] Make model element references consistent (e.g.
PropertyvsIPropertyvsstringvsPropertyInfo) - [x] Add provider-specific extension methods for convention metadata interfaces.
- [x] Rename and move
RelationalAnnotationsandRelationalAnnotationsBuilderto Core. - [x] Remove unused methods on provider classes like
SqlServerPropertyBuilderAnnotations.ColumnName. - [x] Rename the
Applymethods to be more descriptive and make the return types consistent, still allowing to stop the execution of the following conventions. - [x] Pass
CoreConventionSetBuilderDependenciesto the constructor of all conventions. - [x] Add convention type for configuring a type as owned and use it to remove ambiguous ownerships.
- [x] Track the model elements as they are modified by conventions, so a call to a convention never returns an element that is no longer in the model.
- [x] Add a way to delay the convention execution.
- [x] Move logic from
ModelCustomizerto a convention. - [x] Add
SqlServerValueGenerationStrategy.Nonevalue that can be used to override the model default. - [x] Filter out the core annotations changes from conventions.
- [x] Remove
PropertyMetadataChanged()calls and don't cache indexes while the model is mutable. - [x] Expose conventions as
ListonConventionSet - [x] Add methods to add/remove a convention to/from all appropriate convention lists.
- [x] Add a
Conventionsproperty ofConventionSetBuildertype toModelConfigurationBuilderwith methods to add/remove a convention
This was useful for me in the following Scenarios:
- Undo default conventions applied by EF using DbModelBuilder ** Creating an IStoreModelConvention for AssociationType to remove underscore from FK names, ** Creating an IStoreModelConvention for EntitySet to remove underscore from m-2-m join tables/dbsets (not applicable right now to EF Core).
- Dictate Entity Identity Behaviors - using the modelBuilder.Types() method: ** Auto-generation based on whether it's a Data-Dictionary/Lookup item (e.g. BlogType - static) vs an Entity (Blog - autogen). They are distinguished based on interface implementations.
- Decouple code naming standards and DB naming standards - using the modelBuilder.Properties() method: ** Give a common Class property (e.g. "StateId") but an explicit db column name (e.g. "BlogStateId"). Same goes for "Id" in code but "{Type}Id" in database.
Doing this once I was able to govern the entity definitions without requiring explicit entity declaration. I'm not advocating the same implementation, but do feel custom/override conventions are valuable.
Cheers,
Steve
Some of these types of things can be achieved by iterating over the model that is created by convention. This was not possible in EF6 because we collected a set of configuration during OnModelCreating and then used that plus conventions to build the model. But in EF Core we build an initial model from conventions and then pass that to OnModelCreating.
Of course, this means you need to be mindful of ordering. For example, if a type wasn't included in the model by convention, then you need to make sure you add it before you iterate over the model and assign table names.
Here is an example of appending an s to the table name.
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
foreach (var entity in modelBuilder.Model.GetEntityTypes())
{
modelBuilder.Entity(entity.Name).ToTable(entity.Name + "s");
}
}
Thanks for the info Rowan,
I'll just need to explicitly load my entities in this method for my domain assembly:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
var entityTypes = myDomainAssembly.DefinedTypes
.Where(ti => ti.IsClass && ti.IsPublic && !ti.IsAbstract && !ti.IsNested)
foreach (var entityType in entityTypes)
{
modelBuilder.Entity(entityType).ToTable(entity.Name + "s");
}
}
This makes me think that perhaps an OnEntityModelCreating(EntityTypeBuilder entityTypeBuilder) may help with conventions and keep things dynamic.
Steve
I see that this issue is not a priority issue, but will the custom conventions be implemented before RC2, or just before RTM? (I hope it will be at least in RTM)
According to the current roadmap it will be in 7.0.2 (?) https://github.com/aspnet/EntityFramework/wiki/Roadmap
Ohh I missed this. Thank you.
Consider a way to get from IMutableEntityType (or similar) to the InternalEntityTypeBuilder (or similar) so that changes can be flagged as "by convention" when making changes to an IMutableEntityType. See comments on PR #4688.
Regarding
When executing delayed conventions prune redundant ones.
We believe that this could help improve the performance of building the model quite a bit. Currently our benchmarks show that building the AdventureWorks model is marginally slower than in EF6:
InitializationTests.BuildModel_AdventureWorks

cc @AndriySvyryd
See #11404 for details of internal conventions related API that are used by providers.
Also consider https://github.com/aspnet/EntityFrameworkCore/issues/11738 when working on this issue.
Specifically, the comment here: https://github.com/aspnet/EntityFrameworkCore/issues/11738#issuecomment-383703248
@AndriySvyryd can you confirm if this is the right issue for the item "Public conventions (so that providers don't need internal code)" in our planning?
Closed #11404 and #11405 as duplicates of this since providers will need to update to the new public APIs for 3.0,
In case someone comes across this and requires a workaround for snake case table & property names... Here is my workaround (may help the implementation or extensions):
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
foreach (var entity in modelBuilder.Model.GetEntityTypes())
{
// table names
modelBuilder.Entity(entity.Name).ToTable(ToSnakeCase(entity.ShortName() + 's'));
// properties
var props = GetType().Assembly
.GetType(entity.Name)
.GetProperties()
.Where(x =>
x.GetCustomAttribute<NotMappedAttribute>() == null &&
(
x.PropertyType.IsPrimitive ||
(
typeof(Nullable<>).IsAssignableFrom(x.PropertyType) && x.PropertyType.GenericTypeArguments[0].IsPrimitive
) ||
x.PropertyType == typeof(string)
)
);
foreach (var prop in props)
{
modelBuilder.Entity(entity.Name).Property(prop.Name).HasColumnName(ToSnakeCase(prop.Name));
}
}
}
private string ToSnakeCase(string input)
{
var returnString = "";
foreach (var chr in input)
{
if (chr.ToString().ToUpper() == chr.ToString())
{
// is uppercase character
returnString += '_' + chr.ToString().ToLower();
}
else
{
returnString += chr;
}
}
returnString = returnString.TrimStart('_');
return returnString;
}
Planning: we will do here what we can fit into 3.0
Make the opt-in for Enums for 5.0
Any plans to have it in EF Core 5.0 (or even faster, in some preview)?
@Saibamen No, we don't plan to ship this in EF Core 5.0
It's such a common feature I work with oracle and my company insist on using all uppercase for everything
This feature request has been outstanding for over 7 years now and keeps getting pushed back... is there any chance it'll be implemented within this decade?
@IanKemp Yes, some chance.