efcore icon indicating copy to clipboard operation
efcore copied to clipboard

Allow applications to create model building conventions (aka public conventions)

Open rowanmiller opened this issue 12 years ago • 26 comments

  • [x] Create public interfaces for metadata API to be used by conventions.
  • [x] Change QueryFilter, DefiningQuery, IsEagerLoaded, IsShadowProperty , IsIndexedProperty, BeforeSaveBehavior AfterSaveBehavior to extension methods.
  • [x] Throw when calling SetField would change the shadowness of a property or the name of the identifying MemberInfo.
  • [x] Rename GetContainingPrimaryKey to FindContainingPrimaryKey.
  • [x] Throw when calling SetField on 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 explicit ConfigurationSource parameter.
  • [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. Property vs IProperty vs string vs PropertyInfo)
  • [x] Add provider-specific extension methods for convention metadata interfaces.
  • [x] Rename and move RelationalAnnotations and RelationalAnnotationsBuilder to Core.
  • [x] Remove unused methods on provider classes like SqlServerPropertyBuilderAnnotations.ColumnName.
  • [x] Rename the Apply methods to be more descriptive and make the return types consistent, still allowing to stop the execution of the following conventions.
  • [x] Pass CoreConventionSetBuilderDependencies to 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 ModelCustomizer to a convention.
  • [x] Add SqlServerValueGenerationStrategy.None value 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 List on ConventionSet
  • [x] Add methods to add/remove a convention to/from all appropriate convention lists.
  • [x] Add a Conventions property of ConventionSetBuilder type to ModelConfigurationBuilder with methods to add/remove a convention

rowanmiller avatar May 22 '14 20:05 rowanmiller

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

sthiakos avatar Dec 26 '15 18:12 sthiakos

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");
  }
}

rowanmiller avatar Dec 28 '15 19:12 rowanmiller

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

sthiakos avatar Dec 29 '15 02:12 sthiakos

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)

tibitoth avatar Jan 05 '16 12:01 tibitoth

According to the current roadmap it will be in 7.0.2 (?) https://github.com/aspnet/EntityFramework/wiki/Roadmap

ErikEJ avatar Jan 05 '16 12:01 ErikEJ

Ohh I missed this. Thank you.

tibitoth avatar Jan 05 '16 14:01 tibitoth

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.

ajcvickers avatar Mar 03 '16 17:03 ajcvickers

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

image

cc @AndriySvyryd

divega avatar Apr 27 '17 19:04 divega

See #11404 for details of internal conventions related API that are used by providers.

ajcvickers avatar Mar 28 '18 20:03 ajcvickers

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

ajcvickers avatar Apr 23 '18 20:04 ajcvickers

@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?

divega avatar May 17 '18 16:05 divega

Closed #11404 and #11405 as duplicates of this since providers will need to update to the new public APIs for 3.0,

ajcvickers avatar May 21 '18 17:05 ajcvickers

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;
}

MeikelLP avatar Aug 08 '18 20:08 MeikelLP

Planning: we will do here what we can fit into 3.0

ajcvickers avatar Jan 29 '19 00:01 ajcvickers

Make the opt-in for Enums for 5.0

smitpatel avatar Sep 20 '19 18:09 smitpatel

Any plans to have it in EF Core 5.0 (or even faster, in some preview)?

Saibamen avatar Jul 28 '20 19:07 Saibamen

@Saibamen No, we don't plan to ship this in EF Core 5.0

AndriySvyryd avatar Jul 28 '20 19:07 AndriySvyryd

It's such a common feature I work with oracle and my company insist on using all uppercase for everything

Martin-Andersen avatar Sep 09 '20 17:09 Martin-Andersen

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 avatar Oct 28 '21 09:10 IanKemp

@IanKemp Yes, some chance.

ajcvickers avatar Oct 28 '21 09:10 ajcvickers