Skip to content

Add option to ignore all properties for model #14405

Closed as duplicate
Closed as duplicate

Description

@klemmchr

When using a shared model with a lot of properties that should not be mapped it would be helpful to be able to define a property mapping type on the entity. I imagine it like this:

public class MyContext : DbContext
{
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<MyModel>().UseBindingMode(BindingMode.Ignore);
    }
}

public enum BindingMode
{
     /// <summary>
     /// Represents the default binding mode. Public properties will be added to the model.
     /// </summary>
    Default,

     /// <summary>
     /// Represents the ignore binding mode. Public properties will not be added to the model unless explicitly defined.
     /// </summary>
    Ignore
}

Currently it's needed to specify each ignored property separately. When using existing databases and existing models this is a repetitive work and bloats up the model definitions.

Activity

  1. ajcvickers commented on Jan 14, 2019

    @ajcvickers
    Contributor

    Note for triage: as discussed, this is likely covered by public conventions. However, it might be worth keeping this issue open for sugar on top of public conventions based on the current experience which requires:

    • Removing PropertyDiscoveryConvention from two places
    • Removing PropertyMappingValidationConvention, which may have other side effects.

    @Chris579 Some code that works around this by modifying the conventions EF uses is shown below. However, note that this code makes use of internal APIs and as such may be broken in any future release of EF Core. Use at your own risk.

    The general idea is to register a custom SqlServerConventionSetBuilder that removes the property discovery convention. Here's the basic idea

    public class MySqlServerConventionSetBuilder : SqlServerConventionSetBuilder
    {
        public MySqlServerConventionSetBuilder(
            RelationalConventionSetBuilderDependencies dependencies, 
            ISqlGenerationHelper sqlGenerationHelper) 
            : base(dependencies, sqlGenerationHelper)
        {
        }
    
        public override ConventionSet AddConventions(ConventionSet conventionSet)
        {
            conventionSet = base.AddConventions(conventionSet);
    
            // Find the PropertyDiscoveryConvention instance and remove it
            var propertyDiscoveryConvention
                = (PropertyDiscoveryConvention)conventionSet
                    .EntityTypeAddedConventions
                    .SingleOrDefault(c => c.GetType() == typeof(PropertyDiscoveryConvention));
    
            if (propertyDiscoveryConvention != null)
            {
                conventionSet.EntityTypeAddedConventions.Remove(propertyDiscoveryConvention);
                conventionSet.BaseEntityTypeChangedConventions.Remove(propertyDiscoveryConvention);
            }
    
            // Find the PropertyMappingValidationConvention instance and remove it
            var propertyMappingValidationConvention
                = (PropertyMappingValidationConvention)conventionSet
                    .ModelBuiltConventions
                    .SingleOrDefault(c => c.GetType() == typeof(PropertyMappingValidationConvention));
    
            if (propertyMappingValidationConvention != null)
            {
                conventionSet.ModelBuiltConventions.Remove(propertyMappingValidationConvention);
            }
    
            return conventionSet;
        }
    }

    To use this, call ReplaceService when configuring the context:

    public class BloggingContext : DbContext
    {
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder
                .ReplaceService<IConventionSetBuilder, MySqlServerConventionSetBuilder>()
                .UseSqlServer(@"Server=(localdb)\mssqllocaldb;Database=Test;ConnectRetryCount=0");
        }
    }

    Here's a more general version that removes conventions of any type specified:

    public class MySqlServerConventionSetBuilder : SqlServerConventionSetBuilder
    {
        public MySqlServerConventionSetBuilder(
            RelationalConventionSetBuilderDependencies dependencies, 
            ISqlGenerationHelper sqlGenerationHelper) 
            : base(dependencies, sqlGenerationHelper)
        {
        }
    
        public override ConventionSet AddConventions(ConventionSet conventionSet)
            => RemoveConventions(
                base.AddConventions(conventionSet),
                typeof(PropertyDiscoveryConvention),
                typeof(PropertyMappingValidationConvention));
    
        private ConventionSet RemoveConventions(
            ConventionSet conventionSet,
            params Type[] types)
        {
            var conventionLists
                = typeof(ConventionSet)
                    .GetProperties()
                    .Where(p => p.PropertyType.IsGenericType
                                && p.PropertyType.GetGenericTypeDefinition() == typeof(IList<>))
                    .Select(p => (IList)p.GetValue(conventionSet))
                    .ToList();
    
            var conventions = types
                .SelectMany(
                    t => conventionLists
                        .SelectMany(l => l.Cast<object>()
                            .Where(c => c.GetType() == t)))
                .Distinct()
                .ToList();
    
            foreach (var convention in conventions)
            {
                foreach (var conventionList in conventionLists)
                {
                    conventionList.Remove(convention);
                }
            }
    
            return conventionSet;
        }
    }
  2. ajcvickers commented on Jan 16, 2019

    @ajcvickers
    Contributor

    Slightly different workaround, used in the same way, which avoids having to remove the PropertyMappingValidationConvention.:

    public class MyPropertyDiscoveryConvention : PropertyDiscoveryConvention
    {
        public MyPropertyDiscoveryConvention(ITypeMappingSource typeMappingSource) 
            : base(typeMappingSource)
        {
        }
    
        public override InternalEntityTypeBuilder Apply(InternalEntityTypeBuilder entityTypeBuilder)
        {
            var metadata = entityTypeBuilder.Metadata;
            if (metadata.HasClrType())
            {
                foreach (var propertyInfo in metadata.GetRuntimeProperties().Values)
                {
                    if (IsCandidatePrimitiveProperty(propertyInfo))
                    {
                        entityTypeBuilder.Ignore(propertyInfo.Name, ConfigurationSource.Explicit);
                    }
                }
            }
    
            return entityTypeBuilder;
        }
    }
    
    public class MySqlServerConventionSetBuilder : SqlServerConventionSetBuilder
    {
        public MySqlServerConventionSetBuilder(
            RelationalConventionSetBuilderDependencies dependencies, 
            ISqlGenerationHelper sqlGenerationHelper) 
            : base(dependencies, sqlGenerationHelper)
        {
        }
    
        public override ConventionSet AddConventions(ConventionSet conventionSet)
            => ReplayConvention<PropertyDiscoveryConvention>(
                base.AddConventions(conventionSet),
                new MyPropertyDiscoveryConvention(Dependencies.TypeMappingSource));
    
        private ConventionSet ReplayConvention<T>(
            ConventionSet conventionSet,
            T replacementConvention)
        {
            var conventionLists
                = typeof(ConventionSet)
                    .GetProperties()
                    .Where(p => p.PropertyType.IsGenericType
                                && p.PropertyType.GetGenericTypeDefinition() == typeof(IList<>))
                    .Select(p => (IList) p.GetValue(conventionSet))
                    .ToList();
    
            var conventions = conventionLists
                .SelectMany(l => l.Cast<object>()
                    .Where(c => c.GetType() == typeof(T)))
                .Distinct()
                .ToList();
    
            foreach (var convention in conventions)
            {
                foreach (var conventionList in conventionLists)
                {
                    var index = conventionList.IndexOf(convention);
                    if (index >= 0)
                    {
                        conventionList.RemoveAt(index);
                        conventionList.Insert(index, replacementConvention);
                    }
                }
            }
    
            return conventionSet;
        }
    }
  3. ajcvickers commented on Jan 16, 2019

    @ajcvickers
    Contributor

    See also #4356

  4. Dunge commented on Jul 31, 2019

    @Dunge

    This custom convention seems to works when I have an additional property of a basic type like a string (no more 'Invalid column name' error), but doesn't seem to work with properties that are of non-native types.

    For example:
    public KeyValuePair<int, int> SharedTo { get; set; }

    I still get an error in Microsoft.EntityFrameworkCore.Metadata.Internal.Model.Validate:

    System.InvalidOperationException : 'The property 'DeviceBucket.SharedTo' could not be mapped, because it is of type 'KeyValuePair<int, int>' which is not a supported primitive type or a valid entity type. Either explicitly map this property, or ignore it using the '[NotMapped]' attribute or by using 'EntityTypeBuilder.Ignore' in 'OnModelCreating'.'

    In my situation, the C# model is used in a broader scope than just for the database. I have much more properties in my C# model than in my SQL table, and other programmers could had new ones at any time that we don't want to save in the database. As chris579 mentioned, I would prefer having to implicitly specify the properties that are in the database rather than having to implicitly specify those to be ignored.

    In a perfect world, I would have expected EF to only automatically map properties where there is a column of the same name in the database without having to ignore or include explicitly anything other than the exceptions (different names/conversion rules).

    edit:
    After a few more tests, the first two versions of the convention (the one who also remove PropertyMappingValidationConvention) works fine. The alternate one also works if I comment the line with IsCandidatePrimitiveProperty . But I can't really say I understand what this is doing and what impact it would provoke.

    In addition, it doesn't ignore Class type properties, it tries to automatically add them to the list of known entities, and then throw an exception because the key isn't defined. A property of type Tuple throw an exception about the constructor having bad parameters. How can I just tell it to ignore them all?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions